skip to Main Content

Am trying to revert the color and icon of a button when clicked, but I can’t seem to come up with a good approach to deal with the state
The the color and icon only change one time but can’t seem to revert back to the original once clicked again
I just want to be able to switch the color and icon back and forth on every click

Here’s what I’ve tried so far…

code in vs

2

Answers


  1. Chosen as BEST ANSWER
    // Here's a similar solution I just came up with
    
    function App() {
    
        const [isOpen, setIsOpen] = useState(true);
    
        const symbol = () => {
            setIsOpen(s => !s);
        }
    
        return (
            <>
                {
                    isOpen ?
                        <main>
                            <section className="red" onClick={symbol}>✖</section>
                        </main>
    
                        : <main>
                            <section className="green" onClick={symbol}>✔</section>
                        </main>
                }
            </>
        )
    }
    
    

  2. The issue is that your function is setting the icon to a tick and the color to green. Every time you click it it will set it to the same value. I would remove both of this states and put only one – boolean value that checks the state of the button. If it is true, the icon should be a tick and color should be green. If it is false – cross and red.

    const [isClicked, setIsClicked] = useState(false)
    
    return (
      <main>
        <section 
          className={isClicked ? 'green' : 'red'}
          onClick={() => setIsClicked(!isClicked)}          
          >
            {isClicked ? *tick* : *cross*}
          </section>
      </main>
    )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search