|
| 1 | +## Deciding whether to control a form element |
| 2 | + |
| 3 | +- A controlled element lets you have **full control** over its value. |
| 4 | +- An uncontrolled element can let you handle events with less code. |
| 5 | + |
| 6 | +## Controlled form elements |
| 7 | + |
| 8 | +- We store the state for each field using `useState`. |
| 9 | +- We must set the current `value` of the input when rendering. |
| 10 | +- We must listen to when the user changes using `onChange` on each input, and update our state. |
| 11 | +- We can then read our state when the form is submitted. |
| 12 | + |
| 13 | +```tsx |
| 14 | +import React, { useState } from "react"; |
| 15 | +import authService from "../services/auth"; |
| 16 | + |
| 17 | +function SignInForm() { |
| 18 | + const [email, updateEmail] = useState(""); |
| 19 | + const [password, updatePassword] = useState(""); |
| 20 | + |
| 21 | + return ( |
| 22 | + <form |
| 23 | + onSubmit={(event) => { |
| 24 | + event.preventDefault(); // Prevent performing normal submission |
| 25 | + // Could validate here. |
| 26 | + authService.signIn({ email, password }); |
| 27 | + }} |
| 28 | + > |
| 29 | + <label> |
| 30 | + Email |
| 31 | + <input |
| 32 | + type="email" |
| 33 | + value={email} |
| 34 | + onChange={(event) => { |
| 35 | + updateEmail(event.target.value); |
| 36 | + }} |
| 37 | + /> |
| 38 | + </label> |
| 39 | + <label> |
| 40 | + Password |
| 41 | + <input |
| 42 | + type="password" |
| 43 | + value={password} |
| 44 | + onChange={(event) => { |
| 45 | + updatePassword(event.target.value); |
| 46 | + }} |
| 47 | + /> |
| 48 | + </label> |
| 49 | + <button type="submit">Sign In</button> |
| 50 | + </form> |
| 51 | + ); |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +## Uncontrolled form elements |
| 56 | + |
| 57 | +- We have no state — the input itself holds the state. |
| 58 | +- We could set an initial value using `defaultValue`. |
| 59 | +- We don’t have to listen to any change events. |
| 60 | +- We can then read from the form using the DOM when it is submitted. |
| 61 | + |
| 62 | +```tsx |
| 63 | +import React, { useState } from "react"; |
| 64 | +import authService from "../services/auth"; |
| 65 | + |
| 66 | +function SignInForm() { |
| 67 | + return ( |
| 68 | + <form |
| 69 | + onSubmit={(event) => { |
| 70 | + event.preventDefault(); // Prevent performing normal submission |
| 71 | + const email = event.target.elements.email.value; |
| 72 | + const password = event.target.elements.password.value; |
| 73 | + // Could validate here. |
| 74 | + authService.signIn({ email, password }); |
| 75 | + }} |
| 76 | + > |
| 77 | + <label> |
| 78 | + Email |
| 79 | + <input type="email" name="email" /> |
| 80 | + </label> |
| 81 | + <label> |
| 82 | + Password |
| 83 | + <input type="password" name="password" /> |
| 84 | + </label> |
| 85 | + <button type="submit">Sign In</button> |
| 86 | + </form> |
| 87 | + ); |
| 88 | +} |
| 89 | +``` |
0 commit comments