Home > database >  How to use props variables in Tailwind?
How to use props variables in Tailwind?

Time:10-10

I want to delete a css file and rewrite its contents using Tailwind. There is a props in the component and depending on its value different 'size' class should be applied. Tried to write myself, but I do not understand how to do it.

There is a css:

.star {
 margin-left: 10px;

 &.size-l {
   width: 16px;
   height: 16px;
 }

 &.size-m {
   width: 10px;
   height: 10px;
 }
}

raiting component :

export function Raiting ({ stars, size = 'm' }: Props) {
  const getStars = () => {
    const starsArray = [];
    for (let i = 0; i < stars; i  ) {
      starsArray.push(<StarIcon key={i} className={cn(styles.star, styles[`size-${size}`])} />);
    }
    return starsArray;
  };

  return <div>{getStars()}</div>;
}

How can I rewrite StarIcon className to Tailwind?

className={cn(styles.star, styles[`size-${size}`])

CodePudding user response:

You can use a ternary expression with the prop you are passing as a condition to figure out which styles to apply to your icon:

className={size === 'm' ? 'w-2.5 h-2.5' : 'w-4 h-4'}

Or if you want to be a bit more flexible in case you have more sizes to take into account, you could create an enum with all the classes you expect to use and then choose the correct classes with the prop you are passing:

const sizes = {
  s: "w-1.5 h-1.5"
  m: "w-2.5 h-2.5",
  l: "w-4 h-4",
  xl: "w-6 h-6",
}

export const Example = ({ size }) => (
   <div className={`class-1 class-2 ${sizes[size]}`} />
)
  • Related