DEV Community

Discussion on: Controlled Form Inputs using React hooks

Collapse
 
devhammed profile image
Hammed Oyedele • Edited

We can do better using an object, spread operator and computed properties instead of bunch of ifs.

This approach is more scalable and even allow sending the object as JSON easily.

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

export default function App() {
  // Where our state is being stored
  const [form, setForm] = useState({
    name: '',
    username: '',
    email: '',
    password: ''
  })

  // Everytime input changes we update the state
  const handleChange = (e) => {
    setForm(prevForm => ({
       ...prevForm,
       [e.target.name]: e.target.value
    }))
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log('form: ', form)
  }

  // The value will be based on the state
  return (
    <div className="App">
      <h1>Controlled input</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label>name</label>
          <input
            type="text"
            name="name"
            value={form.name}
            onChange={handleChange}
          ></input>
        </div>
        <div>
          <label>username</label>
          <input
            type="text"
            name="username"
            value={form.username}
            onChange={handleChange}
          ></input>
        </div>
        <div>
          <label>email</label>
          <input
            type="email"
            name="email"
            value={form.email}
            onChange={handleChange}
          ></input>
        </div>
        <div>
          <label>password</label>
          <input
            type="password"
            name="password"
            value={form.password}
            onChange={handleChange}
          ></input>
        </div>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
jolouie7 profile image
Joseph Louie

Yea, my approach wasn't the best. I was justing so used to seeing my state separated like that, that I just kept doing it. Your code is so much better and much more scaleable! Thank You for sharing! I'll be doing this from now on!