Lakmal Premaratne
Lakmal Premaratne

Reputation: 1229

React router v6 programmatically redirect

I am in /customerOrders/13 page and from there I try to redirect to /customerOrders/14 using navigate('/customerOrders/14'). Even though the URL is updated, page is not redirected to /customerOrders/14.

Below are code fragments I extracted related to this from the codebase.

App.js

import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
...
<BrowserRouter>
    <Routes>
        <Route path="customerOrders/:id" element={<CustomerOrderForm />}></Route>
    </Routes>
<Router>

CustomerOrderForm.jsx

import { useNavigate  } from "react-router-dom";
...

const CustomerOrderForm = () => {
    let navigate = useNavigate();

    const save = async () => {
        //
        // logic to persist data goes here...
        //

        navigate(`/customerOrders/${customerOrderId}`);
    }
    ...
}

Upvotes: 10

Views: 14487

Answers (2)

Roman
Roman

Reputation: 21757

This solution is independent of whether you are redirecting inside a component or not:

// 1. history.ts
import { createBrowserHistory } from 'history'
export const history = createBrowserHistory()

// 2. index.tsx
import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import { history } from './history.ts'

root.render(
  <HistoryRouter history={history}>
     </div>Hello React Router Redirect Feature</div>
  </HistoryRouter>
);

// 3. Your handle function
import { history } from './history.ts'

const getRedirected = (pathNext = '/') => {
  historyObject.push(pathNext);
  // or
  // historyObject.replace('/');
}

My environment:
"react": "18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.11.0",
"history": "^5.3.0"

Now you can use the history object in any non-react component function

Upvotes: 0

Drew Reese
Drew Reese

Reputation: 202605

When you are on a given route:

<Route path="customerOrders/:id" element={<CustomerOrderForm />} />

and navigating to the same route already rendering the mounted component then the component needs to "listen" for changes to the route, in this case, specifically the id route match param that is updated. Use an useEffect hook with a dependency on the id route match param to rerun any logic depending on it.

import { useNavigate, useParams } from "react-router-dom";

...

const CustomerOrderForm = () => {
  const navigate = useNavigate();
  const { id } = useParams();

  useEffect(() => {
    // rerun logic depending on id value
  }, [id]);

  const save = async () => {
    //
    // logic to persist data goes here...
    //

    navigate(`/customerOrders/${customerOrderId}`);
  };

  ...

};

Upvotes: 20

Related Questions