Episode 27 of 32

Controlled Inputs (Forms)

Build forms in React using controlled inputs with state.

Controlled inputs keep form data in sync with component state.

Creating a Form

const Create = () => {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [author, setAuthor] = useState("Mario");

  return (
    <form>
      <label>Blog Title:</label>
      <input
        type="text"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
      />
      <label>Body:</label>
      <textarea
        value={body}
        onChange={(e) => setBody(e.target.value)}
      />
      <label>Author:</label>
      <select value={author} onChange={(e) => setAuthor(e.target.value)}>
        <option value="Mario">Mario</option>
        <option value="Yoshi">Yoshi</option>
      </select>
      <button>Add Blog</button>
    </form>
  );
};