Skip to content

Commit 6d3a3e2

Browse files
authored
Update forms.md
1 parent 8f7ffa4 commit 6d3a3e2

File tree

1 file changed

+26
-34
lines changed

1 file changed

+26
-34
lines changed

Diff for: content/docs/forms.md

+26-34
Original file line numberDiff line numberDiff line change
@@ -135,44 +135,36 @@ In HTML, `<select>` creates a drop-down list. For example, this HTML creates a d
135135
Note that the Coconut option is initially selected, because of the `selected` attribute. React, instead of using this `selected` attribute, uses a `value` attribute on the root `select` tag. This is more convenient in a controlled component because you only need to update it in one place. For example:
136136

137137
```javascript{4,10-12,24}
138-
class FlavorForm extends React.Component {
139-
constructor(props) {
140-
super(props);
141-
this.state = {value: 'coconut'};
142-
143-
this.handleChange = this.handleChange.bind(this);
144-
this.handleSubmit = this.handleSubmit.bind(this);
145-
}
146-
147-
handleChange(event) {
148-
this.setState({value: event.target.value});
149-
}
150-
151-
handleSubmit(event) {
152-
alert('Your favorite flavor is: ' + this.state.value);
138+
function FlavourForm() {
139+
const [flavour, setFlavour] = useState("");
140+
const handleSubmit = (event) => {
141+
alert(`Your favorite flavor is ${flavour}`);
153142
event.preventDefault();
154-
}
155-
156-
render() {
157-
return (
158-
<form onSubmit={this.handleSubmit}>
159-
<label>
160-
Pick your favorite flavor:
161-
<select value={this.state.value} onChange={this.handleChange}>
162-
<option value="grapefruit">Grapefruit</option>
163-
<option value="lime">Lime</option>
164-
<option value="coconut">Coconut</option>
165-
<option value="mango">Mango</option>
166-
</select>
167-
</label>
168-
<input type="submit" value="Submit" />
169-
</form>
170-
);
171-
}
143+
};
144+
return (
145+
<form onSubmit={handleSubmit}>
146+
<label>
147+
Pick your favorite flavor:
148+
<select
149+
value={flavour}
150+
onChange={(event) => setFlavour(event.target.value)}
151+
>
152+
<option value="grapefruit">Grapefruit</option>
153+
<option value="lime">Lime</option>
154+
<option value="coconut">Coconut</option>
155+
<option value="mango">Mango</option>
156+
</select>
157+
</label>
158+
<input type="submit" value="Submit" />
159+
</form>
160+
);
172161
}
162+
const rootElement = document.getElementById("root");
163+
164+
ReactDOM.render(<FlavourForm />, rootElement);
173165
```
174166

175-
[**Try it on CodePen**](https://codepen.io/gaearon/pen/JbbEzX?editors=0010)
167+
[**Try it on CodeSandBox**](https://codesandbox.io/s/controlled-select-example-fls8j)
176168

177169
Overall, this makes it so that `<input type="text">`, `<textarea>`, and `<select>` all work very similarly - they all accept a `value` attribute that you can use to implement a controlled component.
178170

0 commit comments

Comments
 (0)