Why is my handleChange method being rejected by React?

35 views Asked by At

I am trying to do a simple form task to try and learn React Forms but I am having a hard time understanding the syntax of it.

When I try the following code it works no problem:

import React, { useState } from "react";

function InputForm() {
  const [emailValue, setEmailValue] = useState("");

  console.log(emailValue);

  return (
    <>
      <form>
        <label>
          Email:
          <input
            type="text"
            name="input"
            value={emailValue}
            placeholder="type your email"
            onChange={(e) => setEmailValue(e.target.value)}
          />
        </label>
        <br />
        <br />
        <button type="submit" name="test">
          Submit Email
        </button>
      </form>
    </>
  );
}

export default InputForm;

However, when I try to clean it up so that there is not logic within the return, I get an error when I define my handleChange method.

import React, { useState } from "react";

function InputForm() {
  const [emailValue, setEmailValue] = useState("");

  handleChange(e) {
    const { name, value } = e.target;
    setEmailValue({ [name]: value });
  };

  console.log(emailValue);

  return (
    <>
      <form>
        <label>
          Email:
          <input
            type="text"
            name="input"
            value={emailValue}
            placeholder="type your email"
            onChange={handleChange}
          />
        </label>
        <br />
        <br />
        <button type="submit" name="test">
          Submit Email
        </button>
      </form>
    </>
  );
}

export default InputForm;

Can someone please explain why doing it this way doesn't work? The error I'm getting is that React is not expecting the { bracket after handleChange(e)... so the console error messages are useless in trying to figure out why it's not accepting it.

Thanks!

1

There are 1 answers

2
AKX On

It's not React rejecting anything, it's just that, well, that's not correct JavaScript syntax.

You'll want

function InputForm() {
  const [emailValue, setEmailValue] = useState("");

  const handleChange = (e) {
    const { name, value } = e.target;
    setEmailValue({ [name]: value });
  };

  // ...

(and even so you're mixing and matching state types -- you have a state atom that's ostensibly a string (since you initialize it with a "") and then you assign an object into it... You may be looking for setEmailValue(value); there.)