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?
UPDATE: 2022: React Router v6.6.1 with useNavigate .
The useHistory() hook is now deprecated. If you are using React Router 6, the way to navigate programmatically is: import useNavigate (from “react-router-dom”); .
function HomeButton() const navigate = useNavigate(); .
function handleClick() navigate(“/home”); ‘ .
Return ( button type=”Button” onClick=handle Click>> Go home/ Button> ); .
Hooked React Router v5.1.0 .
In React >16.8.0 and functional components, there is a new useHistory hook in Reacted Router >5.1.0 that imports from “react-router-dom”; .
function HomeButton() const history = useHistory(); .
function handleClick() history.push(“/home”); ‘ .
Return ( button type=”Button” onClick=handle Click>> Go home/ Button> ); .
React Router v4 .
With v4 of React Router, there are three approaches to programmatic routing within components.
Use the context-sensitive withRouter higher-order component. Compose composition and create a ROUTe>.
React Router is primarily a wrapper around the history library. History interacts with the browser’s window history and hash histories for you. If you believe that the location of the current is in the context of your router, HashRouter>, and you’re going to use the new memory history, it will add the properties and methods associated with your current location to the array (react-router) and the methods of memory memory (backback-order component), and will use an array array, which will replace the method of .
A const Button = withRouter(( history) => (button type=”Button’ onClick=()’ (‘ history.push(‘/new-location’), ‘ > Click Me! -/b button> ))
A Route> component isn’t just for matching locations. You can render a pathless route and it will always match the current location. The component of the “ROUTe” passes the same props as with Router, so you can access the history methods by the historical prop. import – Route – from ‘react-router-dom’.
A const Button = () => ( Route render=( history) (Button type=”button’ onClick = ‘plow’ – a . history.push(‘/new-location’) ‘ > Click Me! ‘ /b button> ).
If you are comfortable with React’s context model (React’s Context API is stable as of v16), use the context* but not The last option: => ( button type==”Button’,’ onClick=() ‘ // context.history.push == history.ush (‘/new-location’) – > Click Me! // Button> .
// // you have to specify the type of the context so that it is available within the component Button.contextTypes = history: React.PropTs.shape( push:React: PropTypeS.func.isRequired () .
1 and 2 are the easiest bets to implement for most use cases.