Jason Chen Jason Chen - 3 months ago 14
Javascript Question

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/

QoP QoP
Answer

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

Comments