skip to Main Content

I’m trying to make a dropdown navigation. The idea is to only have one active dropdown when the navigation is clicked and the others close. At the moment it works by the following concept I have but I’m stuck currently where both dropdown is open at the same time when both are clicked.

How can I toggle/add only have one active state and turn the other’s separate function state to false ? please help..

export default function Header(args) {
    const [isActive, setActive] = useState(false);
    const [isResourceActive, setResourceActive] = useState(false);
        
    const handleToggle = () => {setActive(!isActive);};
    const resourcesHandleToggle = () => {setResourceActive(!isResourceActive);};

         return (
    <NavItem onClick={handleToggle} className={isActive ? "active" : ""}></NavItem>  
    <NavItem onClick={resourcesHandleToggle} className={isResourceActive ? "active" :""}</NavItem>
        
        
        <div className={isActive ? "active": ""}>DROPDOWN_1</div>
        <div className={isResourceActive ?"active": ""}>DROPDOWN_2</div>
    )

2

Answers


  1. just force the false for the other dropp (or check it first with a "if" if u want)

    const handleToggle = () => {    
        setActive(!isActive);
        setResourceActive(false);    
    };
       
    
     const resourcesHandleToggle = () => {
        setResourceActive(!isResourceActive);
        setActive(false);    
    };
    
    Login or Signup to reply.
  2. const [active, setActive] = useState(undefined);
    
    const toggle = (name) => {
      if (active === name) {
        setActive(undefined)
      } else {
        setActive(name)
      }
    }
    
    <NavItem onClick={() => toggle('DROPDOWN_1')} className={active === 'DROPDOWN_1' ? "active" : ""}></NavItem>  
    <NavItem onClick={() => toggle('DROPDOWN_2')} className={active === 'DROPDOWN_2' ? "active" :""}</NavItem>
    <div className={active === 'DROPDOWN_1' ? "active": ""}>DROPDOWN_1</div>
    <div className={active === 'DROPDOWN_2' ? "active": ""}>DROPDOWN_2</div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search