I have been struggling to find a good way of accomplishing this, but essentially what I want to do is render a page via the server, but have subsequent routing be client side via react-router. I am able to have a server side router by using createMemoryHistory for my router.
class Router extends React.Component {
render() {
return(
<Router history={createMemoryHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/contact" component={Contact}/>
<Route path="/about" component={About}/>
</Route>
</Router>
)
}
}
Then via the react-rails gem I am able to render the content on the server.
<%= react_component('Router', {}, {prerender: true}) %>
The issue with this is that the URL's don't change when I navigate to different pages. So ideally I'd want to be able to load the router on the server using createMemoryHistory, then once it is loaded I'd want to switch to browserHistory.
You might be able to accomplish this by setting your history prop earlier based on the environment. I am not familiar with the react_component on Rails but I am guessing that MountUp is your root component.
const history = process.env.NODE_ENV === 'server' ? createMemoryHistory : browserHistory;
// ...
class MountUp extends React.Component {
render() {
return (
<Router history={history}/>
);
}
}
// ...
class Routes extends React.Component {
render() {
return(
<Router history={this.props.history}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="/contact" component={Contact}/>
<Route path="/about" component={About}/>
</Route>
</Router>
)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With