JSFiddle - React, Tailwind, and code Playground
http://stackoverflow.com/questions/23028447/how-to-toggle-class-in-the-nested-component-in-reactjs/23032933#23032933
by BinaryMuse
HTML
<script src="http://fb.me/JSXTransformer-0.10.0.js"></script>
<script src="http://fb.me/react-with-addons-0.10.0.js"></script>
<script src="http://fb.me/react-js-fiddle-integration.js"></script>
CSS
.question-a-container { color: red; }
.question-b-container { color: blue; }
.active { font-weight: bold; }
JavaScript 1.7
/** @jsx React.DOM */
// Using classSet to more easily create conditional class names;
// see http://facebook.github.io/react/docs/class-name-manipulation.html
var cx = React.addons.classSet;
var QuestionA = React.createClass({
render: function() {
// always set "question-a-container";
// set "active" if we got a truthy prop named `active`
var className = cx({
"question-a-container": true,
"active": this.props.active
});
return <section className={className}>Section A</section>;
}
});
var QuestionB = React.createClass({
render: function() {
// always set "question-b-container";
// set "active" if we got a truthy prop named `active`
var className = cx({
"question-b-container": true,
"active": this.props.active
});
return <section className={className}>Section B</section>;
}
});
var Root = React.createClass({
getInitialState: function() {
return { question: 'a' };
},
render: function() {
return (
<div className="question">
{/* For each question, compare to state to see if it's active. */}
<QuestionA active={this.state.question === 'a'} />
<QuestionB active={this.state.question === 'b'} />
<div className="question-side-switcher" onClick={this.handleSideChanging}>Change</div>
</div>
);
},
handleSideChanging: function() {
this.setState({question: this.state.question === 'a' ? 'b' : 'a' });
}
});
React.renderComponent(<Root />, document.body);