0

I'm not sure how to look for this but after some looking on here and googling I must not be looking this up correctly.

Here it i'm using a function that applies a className onClick. like so.

  const [isActive, setActive] = useState(false)
  const handleClick = () => [
    setActive(!isActive) 
  ]

// this is the return

     <button onClick={() => {jokes(); handleClick()}}> Get Jokes</button>
          <div className={isActive ? 'card' : ''}>
            <h4>{data?.body?.[0].setup}</h4>
            <p>{data?.body?.[0].punchline}</p>
          </div>

The issue I'm having is once the button is clicked the class name of "card" is applied if the button is clicked again the class name is removed. How can I set it so that once it applies it doesn't remove it with another click?

1 Answer 1

1

This is a logic error, you are flipping the isActive value on each click

 const handleClick = () => [
    setActive(!isActive) 
  ]

the className depends on this value, if you change it, it will remove the class.

It should be

 const handleClick = () => [
    setActive(true) 
  ]
Sign up to request clarification or add additional context in comments.

1 Comment

Wow that is a simple oversight. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.