I am new to ReactJS and JSX and I am having a little problem with the code below.
I am trying to add multiple ways to the className attribute
<ul className="iqacbar-nav" id="iqacbar-nav">
<li className="nav-heading">menu</li>
<li className={isActive('/')} "nav-item">
<Link className="nav-link collapsed active" to="/>
<span> Home</span>
</Link>
</li>
<li className="nav-heading">aboutus</li>
<li className="nav-heading">contactus</li>
<li className="nav-heading">admissions</li>
<li className="nav-heading">courses</li>
<li className="nav-heading">blogs</li>
<li className="nav-heading">reviews</li>
</ul>
`please correct this`
3
Answers
as I understand you want to change the
className
value based on the conditionisActive('/')
what you can do is:Assuming
isActive
function is returning aboolean
. Using this form which called ternary operation (single line if statement) you can tell react that ifisActive
return true then use the first value (nav-item) if not use the second value (empty string).About the Problem
If I am getting it right, you want dynamic ways to add classes in JSX.
Solution
Feel free to comment if you face any further issues
If you want to change styles based on some conditions, I would recommend to use some kind of a tool for constructing classNames strings conditionally, e.x. clsx.
In the example below you can see that I’m changing div background color based on isTurnedOff state value. You can add as many conditions to clsx() function as you want.