Mano
Mano

Reputation: 13

How to toggle css class in react with setState Hook

I tried different ways. But don't manage to toggle this css class. The bookmark should become blue when I click on it. I got so far, I can change to false with onClick, but then it doesn't toggle back.
This is the ToggleBookmark Componenet:

const ToggleBookmark = () => {

const [selected, setSelected]=useState(true);

const  toggleBookmark = () => {
setSelected(true?false:true);
   }

return(
<svg className={`toggleBookmark ${selected ? "toggleBookmark-active" : ""}`} onClick={toggleBookmark} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M22 2v17.582l-4-3.512-4 3.512v-17.582h8zm2-2h-12v24l6-5.269 6 5.269v-24zm-14 1h-10v2h10v-2zm0 5h-10v2h10v-2zm0 5h-10v2h10v-2zm0 5h-10v2h10v-2z"/></svg>
)
}

Upvotes: 0

Views: 905

Answers (3)

Osama Bin Saleem
Osama Bin Saleem

Reputation: 899

You can achieve this by using findDOMNode. This question has been already answered here. Toggle Class in React

For functional components:

setSelected(!selected);

Upvotes: 0

Mano
Mano

Reputation: 13

  const [selected, toggleSelected]=useState(false);
  return(
  <svg className={`toggleBookmark ${selected ? "toggleBookmark-active" : ""}`} onClick={()=>toggleSelected(!selected)} xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M14.568.075c2.202 1.174 5.938 4.883 7.432 6.881-1.286-.9-4.044-1.657-6.091-1.179.222-1.468-.185-4.534-1.341-5.702zm-.824 7.925s1.522-8-3.335-8h-.409v12l-2.5-2.634-2.5 2.634v-12h-3v24h20v-13c0-3.419-5.247-3.745-8.256-3z"/></svg>
 )

And it is working. Thank you

Upvotes: 1

Gal Shacham
Gal Shacham

Reputation: 28

It doesn't turn back because your tri condition is always false. Use selected as the tri condition in order to change back instead of true: On line 5

Upvotes: 0

Related Questions