How can I use the useState function as a toggle method?

Viewed 70
import React, { useEffect, useState } from "react";
import './Menu.css'


export default function Menu() {

const [classes, setClasses] = useState('container')
    return (
        <div>
            <p>Click on the Menu Icon to transform it to "X":</p>
            <div className={classes} onClick={() => setClasses("container change")}>
            <div className="bar1"></div>
            <div className="bar2"></div>
            <div className="bar3"></div>
            </div>
        </div>
    )
}

It works now because of one of the given solutions, but when I click on the icon again, it doesn't go back to the original state. How can I fix that?

I got this menu example from here: https://www.w3schools.com/howto/howto_css_menu_icon.asp

2 Answers

YOu can use state to check what is the current state (user clicked or not), and then can plan behavior accordingly:

export default function Menu() {
  const [toggle, setToggle] = useState(false);
  return (
    <div>
      <p>Click on the Menu Icon to transform it to "X":</p>
      <div
        // If toggle is true, set className to 'change' else 'contianer'
        className={toggle ? 'change' : 'container'}
        // toggle state (toggle) on click
        onClick={() => setToggle(prevToggle => !prevToggle)}
      >
        <div className='bar1'></div>
        <div className='bar2'></div>
        <div className='bar3'></div>
      </div>
    </div>
  );
}

You might want to use useState hook to dynamically change your element's class name.




import React from 'react'
import './Menu.css'


export default function Menu() {

const [classes, setClasses] = useState('container')
    return (
        <div>
            <p>Click on the Menu Icon to transform it to "X":</p>
            <div className={classes} onClick={() => setClasses("container change")}>
            <div className="bar1"></div>
            <div className="bar2"></div>
            <div className="bar3"></div>
            </div>
        </div>
    )
}

Something like this maybe. But I'm sure there are other ways too.

if you want to toggle back and forth;

setClasses(prevClasses => {
if (prevClasses = "container") return "container change" 
else { return "container" }
})

Related