javascriptreactjsreact-router-dom

React router dom v6.10 redirect function isn't working (programmatically redirect)


I've been using redirect method from react-router-dom, since v5, but now it's not working. I've tried useNavigate hook, but then I can't get params through useParams hook. It just doesn't make any redirection to the component defined in the routes. My app was created with create-react-app. Here's my configuration:

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>
);
reportWebVitals();

App.js

import './App.css';
import { Route, Routes } from 'react-router-dom';
import Person from './entities/person/Person';
import UpdatePerson from './entities/person/UpdatePerson';

function App() {
  return (
    <Routes>
      <Route path='/' element={<Person />} />
      <Route path='/update/:id' element={<UpdatePerson />} />
    </Routes>

  );
}

Then in a component rendered inside PersonComponent, I have a button who calls the next function:

const handleEdit = (id) => {
  console.log('Edit clicked, with ID: ', id);
  redirect(`/update/${id}`);
}
...
...
...
<input
  type="button"
  value="Edit"
  onClick={() => handleEdit(person.idPerson)}
/>

I have imported import { redirect } from "react-router-dom" inside the component who calls the previous function. And if I access directly to the route to update component, it works as expected, the only problem is the redirection. What am I missing? Because even in the docs they recommend to use redirect instead of useNavigate hook: Redirect - React Router DOM docs

Or maybe I should use useNavigate hook, and there's other way to get URL params. Just don't tell me to use useLocation because in the docs they say that it returns raw data, and they can provide a better abstraction.

It works now, by using useNavigate instead of redirect function, for redirection, and useParams to get params in the next component, but I want to know if it's possible to use redirect, as it's the recommended option in the docs.


Solution

  • The redirect utility function is only validly used in a data router route's loader or action functions, and is shorthand for returning a 302 response.

    new Response("", {
      status: 302,
      headers: {
        Location: someUrl,
      },
    });
    

    It's not a replacement to the navigate function. You've misunderstood the recommendation, emphasis is mine:

    It's recommended to use redirect in loaders and actions rather than useNavigate in your components when the redirect is in response to data.

    You should still use the useNavigate hook in the React component code to effect a navigation action from a callback.

    Example:

    import { useNavigate } from 'react-router-dom';
    
    ...
    
    const navigate = useNavigate();
    
    ...
    
    const handleEdit = (id) => {
      console.log('Edit clicked, with ID: ', id);
      navigate(`/update/${id}`, { replace: true }); // <-- redirect
    };
    
    ...