Skip to content
Advertisement

React page rendering blank with event listener functions

Having an issue with my code, causing the page to render blank. New to react so any help would be appreciated. I’ve scoured SO to try and find an answer but haven’t found anything that seems to work. I’m aware the syntax for react is incorrect in the functions causing the issue, just looking for some help! Thank you in advance.

Code:

JavaScript

Advertisement

Answer

Forget these kind of usages with React. I mean there might be cases where you’ll have to register special events or selecting DOM elements (which I can recommend useRef hook.) but you don’t need to do that here.

Instead use useState hook for managing the state for your panel.

JavaScript

Don’t forget to do the same for your form submits. Do not use event listeners. Add onSubmit attribute to your forms and change your button types to submit.

Also right now, you are selecting the dom elements and adding event listeners (overriding actually) with each render, each time your component’s state or props change. You can overcome this with useEffect normally but as I said use the way I mentioned above.

Using custom event listeners also has more disadvantages.

  • You have to remove each event listener in cleanup.
  • You are not safe with cross-browser. React uses SyntheticEvent for events which is a cross-browser wrapper around the browser’s native event (https://reactjs.org/docs/events.html)
  • Performance. You are not having the performance boost that SyntheticEvent provides you (event pooling) (not anymore after React v17).
Advertisement