React Router is fun! Here’s how you use it.
Routes are used to render components based on url path — these routes will render the App component with the HomePage or AboutPage as children depending on whether the path is ‘/’ or ‘/about’:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';
const routes = (
<Route path='/' component={App}>
<IndexRoute component={HomePage} />
<Route path='about' component={AboutPage} />
</Route>
);
export default routes;
When the path is ‘/about’, the App component will be rendered (because of the ‘/’ in ‘/about’) with the AboutPage passed as a child component (because of the ‘about’ in ‘/about’).
IndexRoute will let you pass the HomePage as a child component if your path is just ‘/’.
The child component (either HomePage or AboutPage) is passed to the App component in this.props.children. This will render a Header followed by the child component:
import React from 'react';
import Header from './Header';
class App extends React.Component {
render() {
return (
<div>
<Header />
{this.props.children}
</div>
);
}
}
export default App;
Now you can use Router to render your components based on your routes.
import React from 'react';
import { render } from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Router } from 'react-router';
import routes from './routes';
let mountNode = document.getElementById("react-mount");
let router = (
<Router
history={createBrowserHistory()}
routes={routes}
/>
);
render(router, mountNode);
You can use webpack to bundle these files into a single file (that you can then add as a script source in your HTML).
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: [ './main.js' ],
output: {
path: path.join(__dirname, 'public'),
filename: 'main.js'
},
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel-loader'
}]
}
};
Note that this webpack config uses Babel to handle the React/ES6 features we’ve used.
That’s about it!
If this sounds interesting, get in touch! I build websites and apps, and am always happy to chat.