Home > Enterprise >  How to select specific element in react.js
How to select specific element in react.js

Time:03-11

I want to select specific element with className "material-icons-outlined" and add new class to that element

In javascript i would do it like this

document.querySelectorAll(".material-icons-outlined").forEach(icon => {
    icon.classList.add("notranslate");
})

But in react that doesn't work though, so how to do that in a react way?

CodePudding user response:

You can still do that in React, just put those lines in useEffect:

useEffect(() => {
    document.querySelectorAll(".material-icons-outlined").forEach((icon) => {
      // check if already has the class
      if (!icon.classList.contains("notranslate"))
        icon.classList.add("notranslate");
    });
  });

CodePudding user response:

Checkout ref or useRef in reactjs It is your answer.

class App extends React.Component {
    componentDidMount() {
        this.yourRef = React.createRef()
    }
    render() {
        return (
            <div>
                <div id="divR" ref={this.yourRef}>...</div>
            </div>
        )
    }
}
  • Related