Skip to content

Instantly share code, notes, and snippets.

@zakness
Last active January 26, 2018 15:38
Show Gist options
  • Save zakness/bc4d3131f90328654c55033e7f89539e to your computer and use it in GitHub Desktop.
Save zakness/bc4d3131f90328654c55033e7f89539e to your computer and use it in GitHub Desktop.
Programmatic routing with React Router v4

Export the history object you pass to your Router:

import { Router as ReactRouter } from 'react-router-dom'
import { createBrowserHistory } from 'history'

export const history = createBrowserHistory()

const Router = () =>
  <ReactRouter history={history}>
    // routes
  </ReactRouter>

export default Router

Import it as needed:

import { history } from 'Router'

class Register extends React.Component {
  handleSubmit = (user) => {
    saveUser(user).then(() =>
      history.push('/dashboard')
    ))
  }
  render() {
    return (
      <div>
        <h1>Register</h1>
        <Form onSubmit={this.handleSubmit} />
      </div>
    )
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment