React Component Test
by Andre Lee
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JavaScript 1.7
var notify;
var selection = 0;
class SubMenu extends React.Component {
render() {
return (<div>{this.props.children}</div>);
}
}
class Menu extends React.Component {
switch(n) {
selection = n;
if (notify) notify();
}
render() {
return (<SubMenu>
<button onClick={() => this.switch(0)}>Switch to 0</button>
<button onClick={() => this.switch(1)}>Switch to 1</button>
</SubMenu>)
}
}
class Switcher extends React.Component {
constructor () {
super();
notify = () => {
this.setState({selection: selection});
};
this.state = {
selection: 0
}
}
render() {
return this.props.children[this.state.selection];
}
}
class Comp0 extends React.Component {
render() {
return <div>I'm a div</div>;
}
}
class Comp1 extends React.Component {
constructor(props) {
super(props);
this.state = {switch: false};
setTimeout(() => this.setState({switch:true}), 100);
}
render() {
if (this.state.switch) {
return <span>I'm a span</span>;
}
return <div>I'm a text</div>;
}
}
ReactDOM.render(
<div>
<Menu />
<br />
Selected Component:
<Switcher>
<Comp0 />
<Comp1 />
</Switcher>
</div>, document.getElementById('container'));