How to make onChange tracking function in functional component as in class component

The update is similar. Given some state, data for example, then a handler may look like:

const handleChange = (e) => {
  const { id, value } = e.target;
  setData((data) => ({
    ...data,
    [id]: value
  }));
};

Use a functional state update to spread in the existing state and use the input’s id and value from the onChange event to update that section of state.

Edit how-to-make-onchange-tracking-function-in-functional-component-as-in-class-compo

Full code example

function App() {
  const [data, setData] = useState({});

  const handleChange = (e) => {
    const { id, value } = e.target;
    setData((data) => ({
      ...data,
      [id]: value
    }));
  };

  return (
    <div className="App">
      <div className="input-field">
        <label htmlFor="email">Email</label>
        <input type="email" id="email" onChange={handleChange} />
      </div>
      <div className="input-field">
        <label htmlFor="password">Password</label>
        <input type="password" id="password" onChange={handleChange} />
      </div>

      <div>Email: {data.email}</div>
      <div>Password: {data.password}</div>
    </div>
  );
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top