admin管理员组文章数量:1388760
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 bining 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:
Error:
x An object member cannot be declared optional
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 bining 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:
Error:
x An object member cannot be declared optional
Share
Improve this question
edited Jul 18, 2022 at 18:30
Berendschot
asked Jul 18, 2022 at 18:14
BerendschotBerendschot
3,1242 gold badges24 silver badges45 bronze badges
2 Answers
Reset to default 5You 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
You can also use backtick (`) as an alternative like this
<span className=`font-medium ${status ? 'bg-green-600' : 'bg-orange-600' `}>{message}</span>
本文标签: javascriptCombine conditional with static class NextJSStack Overflow
版权声明:本文标题:javascript - Combine conditional with static class NextJS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744619289a2615924.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论