Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change colour of nextjs – tailwind component based on prop

I am creating an alert component in nextjs with tailwindcss to display some information. Ultimately I would like to pass a a prop "alert_type" to this component and based on that change the colour of the alert. (The example below does not have this functionality yet). In the example below I would expect the colour of my alert to be green however, it is not picking up the colour specifications. I don’t understand why this is not working…

export function Success({ title, children }: AlertProps) {
  const colour = 'green'
  return (
    <div className={`rounded-md p-4 bg-${colour}-50`}>
      <div className="flex">
        <div className="flex-shrink-0">
          <CheckCircleIcon
            className={'h-5 w-5' + ' text-' + colour + '-400'}
            aria-hidden="true"
          />
        </div>
        <div className="ml-3">
          <h3 className={'text-sm font-medium' + ' text-' + colour + '-800'}>
            {title}
          </h3>
          <div className={'mt-2 text-sm' + ' text-' + colour + '-700'}>
            {children}
          </div>
        </div>
      </div>
    </div>
  )
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You have to return the complete string as tailwind only parses the complete string. So for instance , like you are using bg-${colour}-500 will be replaced with ${first_var} where you have to define const first_var = bg-green-500;

Then for each time you have to create a new variable like for text-colour-700 and text-colour-800,

Define like this

const sec_var = 'text-green-700';
const third_var = 'text-green-800';
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading