in React JS by
Q:

How do you programmatically navigate using React Router v4?

1 Answer

0 votes
by

There are three different ways to achieve programmatic routing/navigation within components.Using the withRouter() higher-order function:

  1. The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context.

    import { withRouter } from 'react-router-dom' // this also works with 'react-router-native'
    
    const Button = withRouter(({ history }) => (
      <button
        type='button'
        onClick={() => { history.push('/new-location') }}
      >
        {'Click Me!'}
      </button>
    ))
  2. Using <Route> component and render props pattern:

    The <Route> component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.

    import { Route } from 'react-router-dom'
    
    const Button = () => (
      <Route render={({ history }) => (
        <button
          type='button'
          onClick={() => { history.push('/new-location') }}
        >
          {'Click Me!'}
        </button>
      )} />
    )
  3. Using context:

    This option is not recommended and treated as unstable API.

    const Button = (props, context) => (
      <button
        type='button'
        onClick={() => {
          context.history.push('/new-location')
        }}
      >
        {'Click Me!'}
      </button>
    )
    
    Button.contextTypes = {
      history: React.PropTypes.shape({
        push: React.PropTypes.func.isRequired
      })
    }
Click here to read more about React JS
Click here to read more about Insurance

Related questions

0 votes
asked Nov 26, 2019 in React JS by AdilsonLima
0 votes
asked Mar 30, 2020 in React JS by amita rallin
0 votes
asked Mar 2, 2020 in React JS by RShastri
0 votes
asked Nov 26, 2019 in React JS by AdilsonLima
0 votes
asked Mar 2, 2020 in React JS by RShastri
0 votes
asked Mar 4, 2020 in React JS by JackTerrance
0 votes
...