skip to Main Content

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


  1. as I understand you want to change the className value based on the condition isActive('/') what you can do is:

    <li className={isActive('/')? "nav-item" : ""}>
    

    Assuming isActive function is returning a boolean. Using this form which called ternary operation (single line if statement) you can tell react that if isActive return true then use the first value (nav-item) if not use the second value (empty string).

    Login or Signup to reply.

  2. About the Problem

    If I am getting it right, you want dynamic ways to add classes in JSX.



    Solution

    • There can be multiple way to add dynamic classes like

    Use of Ternary Operator

    
     className={isActive('/') ? "hey" : ""};
    
    //if  isActive returns true then classname will be `hey` otherwise "".
    
    
    

    Use of Functions

    className={isActive('/')};
    
    function isActive(val){
    if(val==="/")return "hey";
    return "otherclasses";
    
    }
    
    

    Feel free to comment if you face any further issues


    Login or Signup to reply.
  3. 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.

    import React, { useState } from 'react';
    import clsx from 'clsx';
    
    const Bulb = () => {
      const [isTurnedOff, setIsTurnedOff] = useState<boolean>(true);
    
      return (
        <div>
          <div
            className={clsx(
              'h-10 w-10',
              isTurnedOff ? 'bg-gray-300' : 'bg-yellow-400',
            )}
          />
          <button type="button" onClick={() => setIsTurnedOff(!isTurnedOff)}>
            {isTurnedOff ? 'Turn on' : 'Turn off'}
          </button>
        </div>
      );
    };
    
    export default Bulb;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search