Using map method, how to use multiple classname in React.js?

Viewed 23

please check out my code first.

import styles from './calculator.module.css';

const BUTTONS = [
  {
    key: '+/-',
    styled: 'symbol',
  },
  {
    key: '0',
  },
  {
    key: '.',
    styled: 'symbol',
  },
  {
    key: '=',
    styled: 'equal',
  },
];

const Calculator = () => {
  return (
    <div className={styles.calculator}>
      <section className={styles.buttonGrid}>
        {BUTTONS.map((btn, i) => {
          return (
            <button
              type="button"
              className={`${styles.buttons} ${styles.btn.styled}`} //here is the problem.
              key={`${btn.key}_${i}`}
            >
              {btn.key}
            </button>
          );
        })}
      </section>
    </div>
  );
};

export default Calculator;

Here, I want to use map method and give another classname to style specific components. However, it seems doesn't work.

I tried this way also.

        {BUTTONS.map((btn, i) => {
         
          const customStyle = btn.styled

          return (
            <button
              type="button"
              className={`${styles.buttons} ${styles.customStyle}`}
              key={`${btn.key}_${i}`}
            >
              {btn.key}
            </button>
          );
        })}

and It didn't work well. I have no idea how to solve this problem. How can I get through this?

1 Answers

One of the possible soulutions was this.

className={`${styles.buttons} ${styles[btn.styled]}`}

However, if you try use this format,

const BUTTONS = [
  {
    key: '+/-',
    styled: 'symbol',
  },
  {
    key: '0',
    styled: ''
  },
  {
    key: '.',
    styled: 'symbol',
  },
  {
    key: '=',
    styled: 'equal',
  },
];

You have to add empty string K:V format in the empty ones.

Related