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

Using const in TestCheckbox example #128

Closed
mauron85 opened this issue Nov 18, 2015 · 1 comment
Closed

Using const in TestCheckbox example #128

mauron85 opened this issue Nov 18, 2015 · 1 comment

Comments

@mauron85
Copy link

Why newState is defined as const and in next line you're assigning new field prop to it?

class TestCheckbox extends React.Component {
  state = {
    check1: true,
    check2: false
  };

  handleChange = (field) => {
    const newState = {};
    newState[field] = !this.state[field];
    this.setState(newState);
  };

  render () {
    return (
      <div>
        <Checkbox
          checked={this.state.check1}
          label="Checked option"
          onChange={this.handleChange.bind(this, 'check1')}
        />
        <Checkbox
          checked={this.state.check2}
          label="Unchecked option"
          onChange={this.handleChange.bind(this, 'check2')}
        />
        <Checkbox
          checked
          disabled
          label="Disabled checkbox"
        />
      </div>
    );
  }
}

return <TestCheckbox />;
@javivelasco
Copy link
Member

Because technically newState does not mutate it's value. Changing a prop in the object does not mean changing the value of the variable so no runtime errors. In practice you should use something like ImmutableJS to avoid mutating object but we are not doing it here for simplicity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants