Chi
Chi

Reputation: 326

Can I pass the tailwind className as props in React?

I made a MessageBanner component, and want to make multiple banners like MessageSuccess(green theme) and MessageError(red theme) out from it. And I tried to pass the classNames of background color, text color, and border color but didn't succeed. Please help.

This is the MessageBanner.tsx.

export const MessageBanner: VFC<Props> = memo(props => {
  const { title, description, bgColor, textColor, borderColor } = props
  return (
    <>
      <div
        className={`${bgColor} ${textColor} ${borderColor} pointer-events-autoborder-t-4 rounded-b  px-4 py-3 shadow-md duration-1000`}
        role='alert'
      >
        <div className='flex'>
          <div>
            <p className='font-bold'>{title}</p>
            <p className='text-sm'>{description}</p>
          </div>
        </div>
      </div>
    </>
  )
})

This is the MessageSuccess component. I tried without '.', like 'bg-green-100' instead of '.bg-green-100' but both didn't succeed.

export const MessageSuccess: VFC = () => {
  return (
    <MessageBanner
      title='Welcome Back'
      description='You have successfully logged in'
      bgColor='.bg-green-100'
      textColor='.green-900'
      borderColor='.border-green-500'
    />
  )
}

I appreciate any help. Thanks in advance.

Upvotes: 3

Views: 13616

Answers (1)

You'll probably want to start using the classnames package so you can work with conditional classes much easier, but the main problem is that you've included . in your class names: those are only used in class definitions/query selectors, not when you assign classes, so:

export const MessageSuccess: VFC = () => {
  return (
    <MessageBanner
      title='Welcome Back'
      description='You have successfully logged in'
      bgColor='bg-green-100'
      textColor='green-900'
      borderColor='border-green-500'
    />
  )
}

without the . for those three attributes. Then, you can do:

import { classnames } from "classnames";

const MessageBanner = (props) => {
  const classStr = classnames(
    "pointer-events-autoborder-t-4 rounded-b px-4 py-3 shadow-md duration-1000",
    props.bgColor,
    props.textColor,
    props.borderColor
  );
  return <div className={classStr} role="alert">{props.description}</div>
};

export { MessageBanner }

And things should work just fine.

Upvotes: 5

Related Questions