document.querySelecterAll is not working in react

I am building a simple react app. I am trying to render a JSX element with some labels in it. And I am trying to run javascript code on click on particular querySelectorAll "label" but it is not working when I click on any label present in page. I am new in React.

App.js

class App extends React.Component {
    render() {

        const options = document.querySelectorAll("label");

        for (let i = 0; i < options.length; i++) {
          options[i].addEventListener("click", ()=>{
            console.log(i)
         });
        }

        return (
        <div>
            <label htmlFor="1" className="div-down">
                <span>HTML</span>
            </label>

            <label htmlFor="2" className="div-down">
                <span>JavaScript</span>
            </label>
        </div>
        )
    }
}


export default App;

When I run the above code then it is showing nothing.

I have also tried putting javascript code in .js file and importing it but it is still not working. I have also tried by putting javascript code in index.html file but still not worked

Any help would be much Appreciated. Thank You Very much

>Solution :

As an option you could move the component to functional one and use useEffect there

const App = () => {

        useEffect(() => {
          const options = document.querySelectorAll("label");
          for (let i = 0; i < options.length; i++) {
          options[i].addEventListener("click", ()=>{
            console.log(i)
          });
        }
        }, []);

        

        return (
        <div>
            <label htmlFor="1" className="div-down">
                <span>HTML</span>
            </label>

            <label htmlFor="2" className="div-down">
                <span>JavaScript</span>
            </label>
        </div>
        )
    
}

It will do most likely.

Leave a Reply