Client-side routing with react-router (part 1)
Let’s set up client-side routing with react-router for a universal web application.
Before setting up client-side routing, let’s modularize our ReactRouter routes into its own file.
Remove them from
routes/index.jsx (line 9):
And move them to
A brief description of ReactRouter’s components and methods:
- Router: primary component that keeps your UI and URL in sync
- Route: declaratively maps a route or path to a component.
- browserHistory: uses HTML5 History API.
Alternatively, you can also use hashHistory to keep track of the URL via hashes if you need to support older browsers.
Check out ReactRouter’s API reference to learn more.
client.js to render the ReactRouter elements:
But when we refresh the browser, we get Invariant Violation errors in the
Remember that an Invariant Violation occurs when the rendered elements from the server-side and the client-side do not match.
The error shows up here because the rendered props from the server are not being accounted for on the client.
Let’s fix this by bringing back
window.PROPS (lines 7–11, 14):
Router is the root element of the React app, you’ll need to pass the props there.
We’ll be using Router’s createElement prop in order to merge
window.PROPS with the Router’s own custom props before creating the Router element.
Because the file is used by both the server and client, we need to make sure that the client code only runs in the browser.
We’ll do that by checking for the presence of the
window global because node does not have it defined by default.
Now when your refresh the browser, the console errors are gone. You can check your props and elements with React Developer Tools (Chrome extension).