Home > Blockchain >  Can't make a sidebar appear with an Onclick event in react
Can't make a sidebar appear with an Onclick event in react

Time:06-13

I am a junior software developer and I am trying to make a sidebar appear when I click a hamburger menu. I wrote a function that toggles my state between true and false, but nothing happens. Please help!! Below is my code:

const [isExpanded, setIsExpanded] = useState(true)

const toggleSideNav = () => {
    setIsExpanded(!isExpanded)
    console.log(isExpanded)
    
if (isExpanded == false) {
         return <Fragment />
     } else {
         return <SideBar />
     }

useEffect(() => {
    toggleSideNav()
}, [])

}

<button onClick={toggleSideNav}>
  <FontAwesomeIcon icon={faBars} />
</button>

When I click the button the state toggles as expected, but nothing else happens.

CodePudding user response:

I think that if you return the Fragment/Sidebar like that, you won't be able to render the toggle button once the isExpanded is true. You might want to do something like this instead.

const [isExpanded, setIsExpanded] = useState(true)

const toggleSideNav = () => {
    setIsExpanded(prev => !prev)
}

return{
<Fragment>
  {isExpanded && <SideBar />}
  <button onClick={toggleSideNav}>
    <FontAwesomeIcon icon={faBars} />
  </button>
</Fragment>
} 

By doing this, the Sidebar will only be shown when isExpanded will be true, and the toggle button will be still there to close the Sidebar again

  • Related