Created
October 6, 2015 15:55
-
-
Save vistajess/cb945d09c2705626c5b0 to your computer and use it in GitHub Desktop.
Simple React Toggle On/Off with Multiple Components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Component1 = React.createClass({ | |
render: function() { | |
var txt = this.props.txt; | |
return( | |
<div> | |
<button onClick={this.handleClick().bind(this)}> | |
Toggle {txt} | |
</button> | |
</div> | |
); | |
}, | |
handleClick: function() { | |
return function() { | |
this.props.toggled(); | |
} | |
} | |
}); | |
var Component2 = React.createClass({ | |
render: function() { | |
return( | |
<div> | |
Component2 | |
<Component1 | |
toggled={this.props.toggled} | |
txt={this.props.txt} | |
/> | |
</div> | |
); | |
} | |
}); | |
var App = React.createClass({ | |
getInitialState: function() { | |
return { | |
toggled: false, | |
txt: '' | |
} | |
}, | |
render: function() { | |
return( | |
<div> | |
<Component2 | |
toggled={this.handleToggle().bind(this)} | |
txt={this.state.txt} | |
/> | |
</div> | |
); | |
}, | |
handleToggle:function() { | |
return function() { | |
var txt = this.state.toggled === true | |
? 'On' | |
: 'Off'; | |
this.setState({ | |
toggled: !this.state.toggled, | |
txt: txt | |
}) | |
} | |
} | |
}); | |
React.render( | |
<App/>, | |
document.getElementById('mount') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment