React Forms

Unlike the other HTML Element,form controls keeps some internal state. We can manage the form controls’ state using React component’s states.

Controlled Component

For a Controlled Component, the state is kept in the state property of the component. The state of the component is the “single source of truth”. React component that renders a control also controls what happens in that form on subsequent user input. You are responsible to write the event handler and change the associated component state.

Example of controlled component using text field. The value of the text field is the component state value. onChange event will update the state variable and then cause the input’s value attribute to update.

1
2
3
4
5
6
7
8
9
10
11
12
function TextFieldTest() {
const [firstName, setFirstName] = useState("")
const [lastName, setLastName] = useState("")

return (
<>
<input type="text" placeholder="firstName" value={firstName} onChange={(e) => setFirstName(e.target.value.toUpperCase())} />
<input type="text" placeholder="lastName" value={lastName} onChange={(e) => setLastName(e.target.value.toUpperCase())} />
<p>{`${firstName} ${lastName}`}</p>
</>
)
}

Select

In HTML, <select> creates a drop-down list. You can pass an object with value attribute to the select element

1
2
3
4
5
6
7
8
9
10
11
12
13
function Beverage() {
const [selectedBeverage, setSelectedBeverage] = useState({value:"water"})
return (
<>
<select value={selectedBeverage.value} onChange={e => setSelectedBeverage({value: e.target.value})}>
<option value="water">Water</option>
<option value="tea">Tea</option>
<option value="java">Java</option>
</select>
<button onClick={ () => alert("You order " + selectedBeverage.value)}>Order</button>
</>
)
}

Checkboxes

You can select multiple checkboxes, so the state is an array instead of a single value.

Example of a checkbox group

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
function Beverage() {
const [selectedBeverages, setSelectedBeverages] = useState([])

const handler = (e) => {
const {checked, value}= e.target
if( checked && selectedBeverages.indexOf(value) < 0 ) {
let newValue = [...selectedBeverages]
newValue.push(value)
setSelectedBeverages(newValue)
}else{
setSelectedBeverages([...selectedBeverages].filter(v => v !== value))
}
}
return (
<>
<input type="checkbox" name="beverage" value="water" onChange={e => handler(e)} checked={selectedBeverages.indexOf("water") >= 0} />Water
<input type="checkbox" name="beverage" value="tea" onChange={e => handler(e)} checked={selectedBeverages.indexOf("tea") >= 0} />Tea
<input type="checkbox" name="beverage" value="java" onChange={e => handler(e)} checked={selectedBeverages.indexOf("java") >= 0} />Java
<button onClick={() => alert('order ' + selectedBeverages)} >Order</button>
</>
)
}

Reference