Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading