Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to toggle state with React hook

I had to rewrite a class as a function in JS/React, but I am having some trouble to get the hook to work in the function.

function Switch(props) {
  const [isActive, setIsActive] = React.useState();
  
  function handleClick() {
    setIsActive(!isActive);
  }
 
  const className = `switch ${props.color} ${props.isActive ? 'on' : 'off'}`;

   return (
      <div className={className}>
        <button className="img" onClick={handleClick} />
        <h3>{props.title}</h3>
      </div>
    );
}

ReactDOM.render((
  <Switch title="Happiness" color="blue" isActive={false} />
), document.querySelector('#root'));

I tried changing the handleClick function (and the setIsActive within it), but I can’t get it to work. Thanks in advance for the help!

Note: Didn’t add the CSS, as that part is working fine.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re taking the isActive from props instead from state. To get this working you need to change

const [isActive, setIsActive] = React.useState();

to

const [isActive, setIsActive] = React.useState(props.isActive);

and

const className = `switch ${props.color} ${props.isActive ? 'on' : 'off'}`;

to

const className = `switch ${props.color} ${isActive ? 'on' : 'off'}`;

Also if you want to apply prop changes from outside you need to add an useEffect hook as such

useEffect(() => {
  setIsActive(props.isActive)
}, [props.isActive])  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading