I'm starting to do exercises with React and I wanted to try something small. In JS Vanilla it works fine for me, but in React it doesn't want to catch it and I don't understand. Note that everything that corresponds to ReactDom.render works correctly
Error: TypeError: Cannot read property 'addEventListener' of null.
function App() {
let boton = document.querySelector("#boton");
boton.addEventListener('click', () =>{
document.querySelector("#mensaje").innerHTML="Hola a todos";
})
return (
<div>
<button id="boton">Enviar</button>
<h1 id="mensaje">Mensaje</h1>
</div>
);
}
export default App;
Note that everything that corresponds to ReactDom.render works correctly
your error is that the button has not been rendered yet which is null. React js offers props on elements so you don't have to do an addeventlistener since it's dynamic and the element may not be rendered.
Another way is to call your element in the component lifecycle when it is mounted "ComponentDidMount" in a working component useEffect with empty array dependency to simulate the ComponentDidMount of a comp class. But to handle doom in react it recommends getting its references with the element's ref prop. So you get the element without calling document.queryselector, etc.
In reactjs it is not good practice to use references through the object
document
, you can simply create a function and assign said function through an html attribute, and here is an exampleso we are creating an arrow function and assigning the function to
onClcik
the button eventYou can use react's useRef() hook. For more information, see the Documentation . Also, you should put it in useEffect() or componentWillMount(), it depends if you use classes or functions in your components, for more information Documentation
In case you use functions, in your component:
Note that in useEffect() I put a return that will be executed when the component is unmounted, this way we clean up the eventListener.
Although everything could be simpler if you use the onClick attribute, Documentation
Hope I can help you, good luck!
EDIT
You can also try something like this using findDOMNode :