skip to Main Content

I have a formik form, when I click on the submit button, I want the user to be redirected to /. But it doesn’t work, nothing happens. I don’t think it is useful to past here the code of the component, here is just the React Router route.

<Route exact path = "/create" 
            element = {
            <DepenseForm   
              onSubmit = {(depense) => {  
                console.log("1"); 
                console.log("2"); this.createDepense(depense); 
                console.log("3"); redirect("/")
                console.log("4");}
              } 
            />}
        />

In the console, all numbers are printed 1,2,3,4,5. The createDepense method is also executed.

But the React Router redirect method is not 🙁

No error messages, no warning.

Any clue?

Thanks

2

Answers


  1. You need to use redirect function in react-router-dom v6 like this:

    return redirect("/");
    

    instead of

    redirect("/");
    

    or you can use useNavigate hook.

    import { useNavigate } from 'react-router-dom';
    const navigate = useNavigate();
    navigate('/login', { replace: true });
    
    Login or Signup to reply.
  2. The redirect utility function is only validly used from Data router loader and action functions. It can’t be used in a React component. You should use the useNavigate hook instead and use the navigate function in the callback handler to issue an imperative redirect.

    Since it appears you are passing in a submit handler to the routed component the useNavigate hook will need to be called in the parent component.

    Example:

    const Parent = () => {
      const navigate = useNavigate();
    
      ...
    
      return (
        ...
        <Routes>
          ...
          <Route
            path="/create" 
            element={(
              <DepenseForm   
                onSubmit={(depense) => {  
                  ...
                  createDepense(depense); 
                  ...
                  navigate("/", { replace: true });
                  ...
                }} 
              />
            )}
          />
          ...
        </Routes>
      );
    };
    

    If the parent component is still an older React class component for some reason then you’ll need to create your own custom withRouter Higher Order Component to inject the navigate function as a prop. For more information on this see What happened to withRouter? I need it!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search