0
votes

I've got this straightforward component:

Here it is on CodeSandbox: https://codesandbox.io/s/fast-architecture-fgvwg?fontsize=14&hidenavigation=1&theme=dark

function Home() {
  const [name, setName] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(name);
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input
          value={name}
          onChange={setName}
          type="text"
          placeholder="name"
        />
        <button type="submit">
          submit
        </button>
      </form>
    </>
  );
}

export default Home;

As soon as I click in the input box, it turns into [object object] and I'd love to know why this is happening.

3

3 Answers

1
votes

You are not passing a value to your name variable onChange. onChange returns event which you have to get the value from and set the name that way.

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [name, setName] = useState("");

  const handleSubmit = e => {
    e.preventDefault();
    console.log(name);
  };

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input value={name} onChange={(e) => setName(e.currentTarget.value)} type="text" placeholder="name" />
        <button type="submit">submit</button>
      </form>
    </>
  );
}

The update here is the onChange attribute. You are grabbing the event e and setting the name to whatever that currentTarget value is.

onChange = { (e) => setName(e.currentTarget.value) }
1
votes

Your onChange handler receives a change event object. If you want the new value you'll need to get it from the event: event.target.value:

<input
  value={name}
  onChange={e => setName(e.target.value)}
  type="text"
  placeholder="name"
/>

When you cast a value to a string, like when calling console.log, the value's toString method is invoked, which for objects returns [object Object] by default.

0
votes

You had onChange set to setName. Setname is a function used to update the value of name.

You need to write a function to handle the name value being updating when the user types in a name. Set onChange equal to that function:

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [name, setName] = useState("");

  const handleSubmit = e => {
    e.preventDefault();
    console.log(name);
  };

  function handleChange(e) {
    e.preventDefault();
    setName(e.target.value);
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <input
          value={name}
          onChange={handleChange}
          type="text"
          placeholder="name"
        />
        <button type="submit">submit</button>
      </form>
    </>
  );
}