2

Since React has its own copy of the DOM, what is the best way to modify an HTML element's attributes without affecting React's virtual DOM (Performance)?

Let's say I want to toggle between adding and removing an active class from a list of divs based on their visibility (Intersection Observer)

In Javascript I can just do:

if (inView) {
    element.classList.add('active')
} else {
    element.classList.remove('active')
}

Will this affect React's virtual DOM? If yes can you please suggest the better way to do it?

IAfanasov
  • 4,775
  • 3
  • 27
  • 42
sravis
  • 3,562
  • 6
  • 36
  • 73
  • 4
    Manipulating the DOM within React is generally and anti-pattern. Most times it still works though.. The recommended way would be to use a state variable that serves as the toggle for the class, and then use that toggle to determine what classes a tag should have when rendering your JSX. – Brian Thompson Jun 17 '21 at 13:45
  • Does this answer your question? [React Js conditionally applying class attributes](https://stackoverflow.com/questions/30533171/react-js-conditionally-applying-class-attributes) – Emile Bergeron Jun 17 '21 at 15:27

0 Answers0