Jason Chen
Jason Chen

Reputation: 2577

Reactjs changing states from props?

In my main Duck component I have a state power: off. I would like to be able to switch the power to on by clicking on the visible off string, which is wrapped in a component Lucas inside my main.

In the /**/ tags are where I would like to modify the prop, and subsequently the state of power. I understand that the code below is not supposed to work. But it hopefully gives a clear idea of what exactly I'm trying to accomplish.

var Lucas = React.createClass({

/*
controller:function(){
    this.setProps({power: 'on'});
},
*/

render: function(){
    return (<div><p onClick={this.controller}>{this.props.power}</p></div>);
    }
});

var Duck = React.createClass({
    getInitialState:function(){
    return {power: 'off'}
},

render:function(){
    return (<div>
    <Lucas power={this.state.power}/>
    </div>);
    }
});

Included on JSFiddle https://jsfiddle.net/mfsc3mkx/

Upvotes: 0

Views: 50

Answers (2)

1ven
1ven

Reputation: 7016

In your Lucas component, you should set onClick prop:

var Lucas = React.createClass({
  handleClick: function() {
    this.props.onClick(this.props.power);
  },
  render: function(){
    return (
      <div><p onClick={this.handleClick.bind(this)}>{this.props.power}</p></div>
    );
  }
});

Next, in your Duck component, you need to define onLucasClick callback, and provide it to Lucas onClick prop:

var Duck = React.createClass({
  getInitialState:function() {
    return {
      power: 'off'
    };
  },

  handleLucasClick(power) {
    this.setState({
      power: power === 'on' ? 'off' : 'on'
    });
  }

  render:function() {
    return (
      <div>
        <Lucas power={this.state.power} onClick={this.handleLucasClick.bind(this)} />
      </div>
    );
  }
});

Upvotes: 1

QoP
QoP

Reputation: 28397

You have to create a method in Lucas to change its state, in this case the power value, and pass it to Lucas.

Something like this

var Lucas = React.createClass({
  render: function(){
      return (<div><p onClick={this.props.turnOn}>{this.props.power}</p></div>);
      }
});

var Duck = React.createClass({
    getInitialState:function(){
        return {power: 'off'}
    },
    turnOn: function(){
        this.setState({power : 'on'})
    },
    render:function(){
        return (<div>
             <Lucas power={this.state.power} turnOn={this.turnOn}/>
          </div>);
    }
})

jsfiddle

Upvotes: 1

Related Questions