Search code examples
reactjsweb-applicationsscreenrouter

Redirect after completing an action with react-router-dom V5.+


I'm having trouble with navigating between screen with react-router-dom. What I'm trying to do is that after completing an action I want to navigate to other screen. Sorry for the noob question but it's my first time working with react.


Solution

  • if you are using hooks, use react-router doms useHistory hook https://reactrouter.com/web/api/Hooks

    for example:

    import { useHistory } from "react-router-dom";
    
    function HomeButton() {
      let history = useHistory();
    
      function handleClick() {
        history.push("/home");
      }
    
      return (
        <button type="button" onClick={handleClick}>
          Go home
        </button>
      );
    }