0

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>
)
}

3 Answers 3

1
  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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

For functional components:

setSelected(!selected);

3 Comments

Thank you. I seen that. But I would like to resolve it with Hooks.
As you see I use functional components
setSelected(!selected);

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.