Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React bind in constructor, how to pass parameters to props

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 ;-(

like image 852
user3611459 Avatar asked May 24 '16 11:05

user3611459


1 Answers

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

like image 81
Oleksandr T. Avatar answered Sep 27 '22 20:09

Oleksandr T.