0

What would be the best way of incorporating this JS code with React?

  document.querySelectorAll(".servicesaffectedtag").forEach((tag) => {
    tag.addEventListener("click", (event) => {
      tag.classList.toggle("active-tag");
    });
  });

Is this something that would need to go into the ComponentDidMount() function?

Thanks in advance!

1
  • Using querySelectorAll() and addEventListener() would be the way you'd do things if you weren't using React. In React, you should be defining event behaviour within your render() method Commented Mar 7, 2021 at 12:43

1 Answer 1

1

In react, you can refer to elements using refs. (https://reactjs.org/docs/refs-and-the-dom.html)

However, a better solution would be putting an onClick listener on each element, and changing the class based on state with the ternary operator (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) like this:

<tag 
onClick={() => { classActive ? setClassActive(false) : setClassActive(true) }} className={classActive ? "active-tag" : "" }
>
</tag>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Simon! Any idea on what the state would look like?

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.