Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated form docs to reflect functional set state #9734

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/docs/forms.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class NameForm extends React.Component {
}

handleChange(event) {
this.setState({value: event.target.value});
this.setState(() => ({value: event.target.value}));
}

handleSubmit(event) {
Expand Down Expand Up @@ -72,7 +72,7 @@ With a controlled component, every state mutation will have an associated handle

```javascript{2}
handleChange(event) {
this.setState({value: event.target.value.toUpperCase()});
this.setState(() => ({value: event.target.value.toUpperCase()}));
}
```

Expand Down Expand Up @@ -101,7 +101,7 @@ class EssayForm extends React.Component {
}

handleChange(event) {
this.setState({value: event.target.value});
this.setState(() => ({value: event.target.value}));
}

handleSubmit(event) {
Expand Down Expand Up @@ -151,7 +151,7 @@ class FlavorForm extends React.Component {
}

handleChange(event) {
this.setState({value: event.target.value});
this.setState(() => ({value: event.target.value}));
}

handleSubmit(event) {
Expand Down Expand Up @@ -205,9 +205,9 @@ class Reservation extends React.Component {
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;

this.setState({
this.setState(() => ({
[name]: value
});
}));
}

render() {
Expand Down Expand Up @@ -241,17 +241,17 @@ class Reservation extends React.Component {
Note how we used the ES6 [computed property name](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names) syntax to update the state key corresponding to the given input name:

```js{2}
this.setState({
this.setState(() => ({
[name]: value
});
}));
```

It is equivalent to this ES5 code:

```js{2}
var partialState = {};
partialState[name] = value;
this.setState(partialState);
this.setState(() => partialState);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is no longer ES5 code 😯

```

Also, since `setState()` automatically [merges a partial state into the current state](/react/docs/state-and-lifecycle.html#state-updates-are-merged), we only needed to call it with the changed parts.
Expand Down