Skip to content
Advertisement

Set active class conditionally in React

I am new to React and of course, I am facing problems, the thing I am trying to accomplish is this. When any of these Components is opened I want to set an active class. I have already tried something but it is not working. So I want to add a background color to these divs className='menu__iconsRight ' when they are active. I would appreciate the help. Thanks

 const App = () => {

 const[isStyleOpen, setIsStyleOpen]=React.useState(false)
 const[isRectOpen, setIsRectOpen]=React.useState(true)
 const[isHairOpen, setIsHairOpen]=React.useState(false)

    function openHair(){
    setIsHairOpen(true)
    }
    function closeHair(){
      setIsHairOpen(false)
    }

     
    function openRect(){
     setIsRectOpen(true)
    }
    function closeRect(){
      setIsRectOpen(false)
     }
 
    

    function openStyle(){
     setIsStyleOpen(true)
    }
    function closeStyle(){
     setIsStyleOpen(false)
    }


     return (
      
          <div className='menu'>         
            <div className='menu__iconsRight ' >
            <img   onClick={() => setIsRectOpen(!isRectOpen)} 
              src="./images/icons/win.png"/>
              {isRectOpen ? <Rect />: null}
          </div>
       
           
            <div className={`?active: 'menu__iconsRight' `}    >
            <img    onClick={() => setIsStyleOpen((isStyleOpen) => 
             !isStyleOpen)} 
              src="https://winaero.com/blog/wp-content/uploads/2017/07/Co-win-- 
              icon.png"/>
               {isStyleOpen ? <Style  closeStyle={closeStyle}  />: null}
            </div>
       
              <div className='menu__iconsRight '>
                <img    onClick={() => setIsHairOpen(!isHairOpen)} 
              src="./images/icons/at.png"/>
               {isHairOpen ? <Hair closeHair={closeHair}  />: null}   
               </div>
              
            )
           }
         export default App

Advertisement

Answer

You can simply do something like:

...
<div className={"menu__iconsRight " + ((isRectOpen) ? "active": "")}>
...

Is this what you’re looking for?

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement