How to Programmatically navigate using React router?
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(...).
If I want to do a navigation not from a link, but from a dropdown selection for example.
How can I do this in code?
You can use
For React Router v4+
UseNavigate
You can use useNavigate for simplicity
import { useNavigate } from "react-router-dom";
const Newfile = () => {
const navigate = useNavigate();
....
navigate("yourdesiredlocation");
....
}
export default Newfile;
There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.
UseHistory
import { useHistory } from "react-router-dom";
function HomeButton() {
const history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
import { useHistory } from 'react-router-dom';
const Component = (props) => {
const history = useHistory();
// Programmatically navigate
history.push(newUrlString);
}
withRouter
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>
))
You might Also Like