Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a conditional statement in my JSX

<li className=`nav-item {(this.props.activeState===1) ? "active":""}`><a href="#">Main</a></li>

^ This is my code. I want the classname "active" to appear next to "nav-item" if the condition is met. I thought putting backticks lets me use text and code together, but I am getting an error - JSX value should be either an expression or a quoted JSX text

How do I properly do this?

like image 889
Raven Avatar asked Feb 06 '26 12:02

Raven


1 Answers

You need to make the entire template string a JSX prop expression:

<li className={`nav-item ${(this.props.activeState === 1) ? "active": ""}`}>
  ...
</li>

It might be cleaner to use a variable:

const activeClass = (this.props.activeState === 1) ? "active": "";
// ...
<li className={`nav-item ${activeClass}`}>
  ...
</li>
like image 166
nem035 Avatar answered Feb 08 '26 00:02

nem035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!