React Base Fiddle (JSX)
Starting point for creating JSFiddles with React. This uses React with Addons.
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://unpkg.com/react-router-dom/umd/react-router-dom.min.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="root"></div>
JavaScript 1.7
class ChildOne extends React.Component {
render() {
return (
<h2>Component 1</h2>
)
}
}
class ChildTwo extends React.Component {
render() {
return (
<h2>Component 2</h2>
)
}
}
var unlisten;
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
childPath: null
};
}
componentDidMount() {
unlisten = this.props.history.listen((location, action) => {
if(location.pathname === "/component1" || location.pathname === "/component2") {
if(location.pathname !== this.state.childPath) {
this.setState({
childPath: location.pathname
});
}
}
});
}
componentWillUnmount() {
unlisten();
}
handleNavComponent(ev, path) {
ev.preventDefault();
const { history } = this.props;
this.setState({
childPath: path
});
history.push(path);
}
renderChildComponent(event) {
const { history } = this.props;
const { childPath } = this.state;
return (
(history && history.location && history.location.pathname) ? <DynamicRoute path={`${childPath}`} component={childPath === "/component1" ? ChildOne : ChildTwo} /> : null
);
}
render() {
const { location } = this.props;
const { childIndex } = this.state;
return (
<div>
<ul>
<li><a href="#" onClick={ev => this.handleNavComponent(ev, "/component1")}>Child 1</a></li>
<li><a href="#" onClick={ev => this.handleNavComponent(ev, "/component2")}>Child 2</a></li>
</ul>
{this.renderChildComponent()}
<button onClick={() => this.props.history.goBack()} disabled={location.pathname === "/"}>Go Back</button>
</div>
)
}
}
const DynamicRoute = (props => {
const { Route } = ReactRouterDOM;
return (
<Route path={props.path} component={props.component} />
);
});
class App extends React.Component {
render() {
...