简体   繁体   中英

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

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?

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>
  );
};

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

You could use ternary condition check for this.

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

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>
  );
};

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM