How to programmatically navigate using React Router?

clock icon

asked 11 months ago.

Answers

3 Answers

eye

34 views

With react-router I can use the Link element to create links which are natively handled by react router.

I see internally it calls this.context.transitionTo(...).

I want to do a navigation. Not from a link, but from a dropdown selection (as an example). How can I do this in code? What is this.context?

I saw the Navigation mixin, but can I do this without mixins?

3 Answers

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

I don't know this questions 

 Use the withRouter higher-order component

The withRouter higher-order component will inject the history object as a prop of the component. This allows you to access the push and replace methods without having to deal with the 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>
))
 

1

Write your answer here

Top Questions