3

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.

1 Answer 1

2

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>
    )
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.