Home > Software engineering >  React add className issue
React add className issue

Time:03-30

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?

CodePudding user response:

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) 
  ]
  • Related