Search code examples
reactjsjsxonchange

Using Onchange in JSX (React)


I'm implementing contact-form functionality into a bigger project. The form works fine separately, though it's written in JS (you can find it here. My bigger project is however, set up in JSX, where I get an error as soon as I type into an input-field. The error points at line 22 of the code, saying the respective field is null. When I log the value it is, indeed, not retrieving anything from what has been added. Here is the code snippet of where it happens:

const [mailerState, setMailerState] = useState({
    name: "",
    email: "",
    message: "",
  });

  const captchaRef = useRef(null);
  
  function handleStateChange(e) {
    setMailerState((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value, <<<< The error codes points here >>>>
    }));
    console.log(mailerState);
  }

my input fields look like this:

<input
           placeholder="Name"
           onChange={handleStateChange}
           name="name"
           value={mailerState.name}
         />

Error message:

Uncaught TypeError: Cannot read properties of null (reading 'name')
    at Kontakt.jsx:22:1
    at basicStateReducer (react-dom.development.js:15013:1)
    at updateReducer (react-dom.development.js:15135:1)
    at updateState (react-dom.development.js:15237:1)
    at Object.useState (react-dom.development.js:15949:1)
    at useState (react.development.js:1497:1)
    at Kontakt (Kontakt.jsx:11:1)
    at renderWithHooks (react-dom.development.js:14803:1)
    at updateFunctionComponent (react-dom.development.js:17034:1)
    at beginWork (react-dom.development.js:18610:1)

I suspect JSX wants this handled a little differently. I've also tried onBlur but get the same results. I'm still learning the finer details of using JSX, so would appreciate any help and pointers. Many thanks!


I've whittled it down to a skeleton for GitHub. The issue still happens for me, but bare in mind the message will not send like this. The full Kontakt.jsx is here, and the rest of the React-setup is along with it.


Solution

  • After seeing the example and discussing the output it seems the issue stems from the fact that you're using React and are getting a synthetic event which sometimes has an odd behavior.

    I am by no means an expert, but I think this answer is all you need to know in order to get this code to work properly. Alternatively as per the warning you get, you could try to call e.persist(), though I am not sure if this could cause other issues.

    Should probably also read up on synthetic events to understand what's going on.