9

I am trying to convert my React classes to ES6, but I am having some difficulty within this process.. I would like to have my bindings in the constructor, not in the render view.

Now, if I have a root module with a setState which needs a parameter, e.g.:

constructor() {
    super();

    this.state = {
        mood: ""
    };

    this.updateMood(value) = this.updateMood.bind(this,value);
}

updateMood(value) {
    this.setState({mood: value});
}

Then I pass this function to a component:

<customElement updateMood={this.updateMood}></customElement>

Then within the customElement module, I have something like this:

constructor() {
    super();
}

update(e) {
    this.props.updateMood(e.target.value);
}

and in the render:

<input onChange={this.update} />

Is this the correct way? Since I can't get it to work ;-(

2
  • Just remove this.updateMood(value) = this.updateMood.bind(this,value); and change <customElement updateMood={this.updateMood.bind(this)}></customElement> Notice bind this while providing in props. Commented May 24, 2016 at 12:09
  • "Is this the correct way?" If it doesn't work then probably not :P All you need is this.updateMood = this.updateMood.bind(this);. You should read the documentation about .bind and about functions in general to get a better understanding about how they work. This has nothing to do with React or ES6 btw. Commented May 24, 2016 at 16:11

2 Answers 2

7

You can't use this this.updateMood(value) = this.updateMood.bind(this,value); construction, because it is syntax error.

You can solve your problem like this

class CustomElement extends React.Component {
  constructor() {
    super();
    this.update = this.update.bind(this);
  }

  update(e) {
    this.props.updateMood(e.target.value);
  }

  render() {
    return <input onChange={this.update} />
  }
}

class Parent extends React.Component {
  constructor() {
    super();

    this.state = {
        mood: ""
    };

    this.updateMood = this.updateMood.bind(this);
  }

  updateMood(value) {
    this.setState({ mood: value });
  }

  render() {
    return <div>
      <CustomElement updateMood={this.updateMood}></CustomElement>
      <h1>{ this.state.mood }</h1>
    </div>
  }
}

Example

Sign up to request clarification or add additional context in comments.

Comments

0

Or, depending on your babel settings, or when using typescript, the following achieves the same but is a lot more convenient to write / maintain:

class Parent extends React.Component {
  constructor() {
    super();

    this.state = {
        mood: ""
    };
  }

  updateMood = (value) => {
    this.setState({ mood: value });
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.