How to programmatically navigate using React Router?

UPDATE: 2022: React Router v6.6.1 with useNavigate The useHistory() hook is now deprecated. If you are using React Router 6, the proper way to navigate programmatically is as follows: import { useNavigate } from “react-router-dom”; function HomeButton() { const navigate = useNavigate(); function handleClick() { navigate(“/home”); } return ( <button type=”button” onClick={handleClick}> Go home </button> … Read more

In React Router v6, how to check form is dirty before leaving page/route

Update: Prompt, usePrompt and useBlocker have been removed from react-router-dom. This answer will not currently work, though this might change. The github issue, opened Oct 2021, is here The answer… This answer uses router v6. You can use usePrompt. usePrompt will show the confirm modal/popup when you go to another route i.e. on mount. A … Read more

How to mock react-router context

Thanks @Elon Szopos for your answer but I manage to write something much more simple (following https://github.com/airbnb/enzyme/pull/62): import NavLink from ‘../index’; import expect from ‘expect’; import { shallow } from ‘enzyme’; import React from ‘react’; describe(‘<NavLink />’, () => { it(‘should add active class’, () => { const context = { router: { isActive: (a, … Read more

How to redirect to a new page from a function in React?

If you use the react-router-dom package you can wrap your component with a router and then you have the ability to redirect the user programmatically, like so this.props.history.push(‘/login’). Eg: import {withRouter} from ‘react-router-dom’; class Component extends React.component { constructor(props){ } componentDidMount(){ this.props.history.push(‘/login’); } } export default withRouter(Component); See: https://www.npmjs.com/package/react-router-dom.