Skip to content

Instantly share code, notes, and snippets.

@chrisirhc
Created September 21, 2015 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisirhc/de91ace4e7a44ed897b7 to your computer and use it in GitHub Desktop.
Save chrisirhc/de91ace4e7a44ed897b7 to your computer and use it in GitHub Desktop.
xwOgJX
var Container = React.createClass({
getInitialState: function () {
return {
contentComponent: ContentA,
headerProps: null
};
},
_toggleContent: function () {
this.setState({
contentComponent:
this.state.contentComponent === ContentA ? ContentB : ContentA
});
},
setHeaderProps: function (props) {
this.setState({
headerProps: props
});
},
render: function () {
return (
<div>
<button onClick={this._toggleContent}>Toggle Content</button>
<HeaderContent {...this.state.headerProps} />
<section>
<this.state.contentComponent
setHeaderProps={this.setHeaderProps} />
</section>
</div>
);
}
});
var ContentA = React.createClass({
componentWillMount: function () {
this.props.setHeaderProps({
style: {
backgroundColor: '#eee'
},
content: <button onClick={this._click}>Button from ContentA</button>
});
},
_click: function () {
this.setState({buttonClicked: true});
},
render: function () {
return (
<div>
<h2>ContentA</h2>
Button clicked?{' '}
{this.state && this.state.buttonClicked && 'true' || 'false'}
</div>
);
}
});
var ContentB = React.createClass({
componentWillMount: function () {
this.props.setHeaderProps({
content: <button onClick={this._click}>Button from ContentB</button>
});
},
_click: function () {
this.setState({buttonClicked: true});
},
render: function () {
return (
<div>
<h2>ContentB</h2>
Button clicked?{' '}
{this.state && this.state.buttonClicked && 'true' || 'false'}
</div>
);
}
});
var HeaderContent = React.createClass({
render: function () {
return (
<header>
<h2>HeaderContent</h2>
{this.props.content}
</header>
);
}
});
var element = React.createElement(Container);
React.render(element, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.min.js"></script>
html {
font-family: Helvetica Neue;
}
header, section {
border: 1px solid #eee;
margin-bottom: 10px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment