skip to Main Content

I have a div that i want its width to switch between 260px and 85px as i click on a button (that will trigger an useState), but i tried a few different ways and none is giving me the result im looking for.
Heres my code (without trying to apply the usestate in the navs classname):

export function Menu(){
const [expanded, setExpanded]= useState(true);
return(
    <aside className="h-screen">
        <nav className= {'h-full flex flex-col bg-sidebar w-[260px]'}>
            <div>
                <button onClick={()=>setExpanded((curr)=> !curr)}>
                <img src="/Menu.png" alt="menuLogo" className="absolute top-4 ml-[23px]"/>
                </button>
            </div>
        </nav>

2

Answers


  1. You have to make the nav Tailwind class dependent on the expanded state:

    <nav className={'h-full flex flex-col bg-sidebar ' + (expanded ? 'w-[260px]' : 'w-[85px]')}>
        <div>
            <button onClick={()=>setExpanded((curr)=> !curr)}>
                <img src="/Menu.png" alt="menuLogo" className="absolute top-4 ml-[23px]"/>
            </button>
        </div>
    </nav>
    
    Login or Signup to reply.
  2. You can make use Javascript template literals to achieve your goal.

    Ideally, this is what you will have to do:

    export function Menu(){
    const [expanded, setExpanded]= useState(true);
    return(
        <aside className="h-screen">
            <nav className= {`h-full flex flex-col bg-sidebar transition-all duration-500 ${expanded ? 'w-[260px]' : 'w-[85px]'}`}>
                <div>
                    <button onClick={()=>setExpanded((curr)=> !curr)}>
                    <img src="/Menu.png" alt="menuLogo" className="absolute top-4 ml-[23px]"/>
                    </button>
                </div>
            </nav>
        </aside>
    )}
    

    I also added a Tailwind’s transition utilities for a smooth transition both ways. Hope this helps 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search