0

I am using react-router-dom v6.4 and I am wondering if I can do something. I want to pass data to another route when I redirect.

I know that in the previous version I can use the state prop:

<Redirect
  to={{
    pathname: "/login",
    state: { referrer: currentLocation }
  }}
/>

However, using redirect() that doesn't work:

import { Form, redirect } from "react-router-dom";

export function action() {
  return redirect("/home", { state: { value: 5 } });
}

export default function Blog() {
  return (
    <Form method="post">
      <button>Submit</button>
    </Form>
  );
}
import { useLocation } from "react-router-dom";

export default function Home() {
  const location = useLocation();
  console.log(location.state.value);
  return <div>Home</div>;
}

Is there a way to send data when redirecting?

1 Answers1

0

Accroding to react-router-dom version : 6.x you have to use the <Navigate /> instead of <Redirect /> and you can pass the url in that component

Also, to pass the state values you have to replace the redirect("/home", { state: { value: 5 } }) with navigate("notifications", {state: { value: 5 }}) where navigate is defined as const navigate = useNavigate(); and imported from the react-router-dom with import { useLocation, useNavigate } from "react-router-dom";

So your code will be,

import { Navigate } from "react-router-dom";    
<Route
   path="/" 
   element={<Navigate to="/login" />}
/>

then use navigate

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

export function action() {
    const navigate = useNavigate();
    return navigate("/home", { state: { value: 5 } });
}

export default function Blog() {
  return (
    <Form method="post">
      <button>Submit</button>
    </Form>
  );
}

and you will recieve the values in location.state.value.

Hetal N
  • 158
  • 8