Home > other >  How to conditionally apply classNames (JIT) with Tailwind and React? [Resolved]
How to conditionally apply classNames (JIT) with Tailwind and React? [Resolved]

Time:09-23

I have the following object map:

const stylesMap = {
  level: {
    1: "text-5xl",
    ...
  },
};

In my component I have:

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1 className={classNames(stylesMap.level[level ?? stylesMap.level[1]])}>
      Test
    </h1>
  );
};

As a test I have made level: null expecting the values "text-5xl" to be part of the classNames list but I don't see it. I'm simply trying to set default values if the props are null.

I even add safelist: ["text-5xl"] in the tailwindcss config but that didn't work even though its already picked up in stylesMap Am I missing anything?

CodePudding user response:

I know what happened. I was passing the actual value instead of the key.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1 className={classNames(stylesMap.level[level ?? 1])}>
      Test
    </h1>
  );
};

CodePudding user response:

you can use clsx library. It's used for applying classNames conditionally.

<h1 className={clsx({[stylesMap.level[1]: level]})}>
   Test
</h1>

Ex:

const menuStyle = clsx({
        [classes.root] : true, //always applies
        [classes.menuOpen] : open //only when open === true
    })

For your reference: https://www.npmjs.com/package/clsx

CodePudding user response:

You could use ternary condition check for this.

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1 className={level === null ? "text-5xl" : null}>
      Test
    </h1>
  );
};

CodePudding user response:

You can try it this way

const ComponentExample = (props) => {
  const { level } = props;
  return (
    <h1
      className={
        stylesMap?.level && stylesMap?.level[1]
          ? stylesMap.level[1]
          : 'text-5xl'
      }
    >
      Test
    </h1>
  );
};

CodePudding user response:

Condition = condition to check for deciding which className to give

trueValue = the className to give in case the condition is true

falseValue = the className to give in case the condition is false

<h1 className={condition ? trueValue : falseValue}>
     Test
</h1>
  • Related