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

Combine conditional with static class NextJS

In NextJS I’m trying to apply both a static CSS-class and a conditional class to an element. Separated from each other I can make both work, but when combining them it will result in an unexpected error.

# This will work
<span className="font-medium">{message}</span>

# This will work too
<span className={status ? "bg-green-600":"bg-orange-600"}>{message}</span>

In Visual Studio the following snippet will give an error ',' expected.ts(1005)

# This (where I'm trying to apply *both* classes to the same element) won't work
<span className={"font-medium" + {status ? "bg-green-600":"bg-orange-600"}}>{message}</span>

Ignoring that will give following error:

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

Error: 
  x An object member cannot be declared optional

>Solution :

You need a space after font-medium, because it will be interpreted as a single class otherwise

<span className={"font-medium " + status ? "bg-green-600":"bg-orange-600"}>{message}</span>

And with template literals :

<span className={'font-medium ${status ? "bg-green-600" : "bg-orange-600" }'}>{message}</span>

(Please note it’s `and not ‘ here)

In this type of cases, dont forget to debug by inspecting the element and checking the classes

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