useState, setting icon active and inactive

Viewed 730

Hi all I have following code : my code

I have two useStates, they checking if first one is true then they set active icon if false then inactive icon.

    const [icon, setIcon] = useState(false);
    const [v, setV] = useState(Viber);
     function handleClick() {
       setIcon(true);
       icon ? setV(Viber) : setV(ViberChecked);
       setIcon(false);
     }

    return (
        <div className="App">
          <img src={v} alt="icon" onClick={handleClick} />
        </div>
     );

I think it working in right way, but it works only one time, how can I change my state after all clicks, I mean to set inactive then after click from inactive to active and so on.It should be like something as checkbox

Please help me to resolve this issue, thanks.

4 Answers

You literally set icon to true, then check if icon is true, then set icon false. Why is that? Your icon will always be true in this case

You can do something like this instead: (Check the working sandbox )

function handleClick() {
       if(icon){
         setV(Viber)
         setIcon(false)
       }else{
         setV(ViberChecked);
         setIcon(true);
       }
     }

you can change your code:

import React, { useState, useEffect } from "react";
import "./styles.css";
import Viber from "./viber.svg";
import ViberChecked from "./viberChecked.svg";
export default function App() {
  const [icon, setIcon] = useState(true);
  const [v, setV] = useState(Viber);
  useEffect(() => {
    icon ? setV(Viber) : setV(ViberChecked);
  })
  // function handleClick() {
  //   setIcon(true);
  //   icon ? setV(Viber) : setV(ViberChecked);
  //   setIcon(false);
  // }
  return (
    <div className="App">
      <img src={v} alt="icon" onClick={() => setIcon(!icon)} />
    </div>
  );
}

You are clicking on the icon to make it true

  setIcon(icon => !icon)

or

<img src={v} alt="icon"  onClick={e => setIcon(!icon )} />

you cannot use the var right away in hooks. maybe add a useEffect that depends on the icon variable.

  useEffect(() => {
    // do your stuff
  }, [icon]);
Related