Home > Enterprise >  How to access data from location in react-router-dom 6
How to access data from location in react-router-dom 6

Time:12-22

Working on a 'forgot password' functionality, I am trying to pass the email data from the 'login page' to the 'forgot password' page through Link.

But when I am trying to access the same in the 'forgot password' page, it is giving me undefined.

Could you please check my syntax?

Below is the code-snippet and the code of the 'login page':

<div className="forget-password-container">
   <div>
       {" "}
       <Link to={{
          pathname: "/forget-password",
          state: formData.email,
       }}>
          <u style={{ textDecoration: "underline" }}>Forgot Password</u>
       </Link>
    </div>
</div>

Forget Password Page:

const ForgetPassword = (props) => {
   // const { email } = (props.location && props.location.state) || {};
   console.log(props?.location?.state);
   return <div>ForgetPassword </div>;
 };
        
export default ForgetPassword;

Please suggest to me how can I access the mail data on the 'forgot password' page

CodePudding user response:

state should be outside to.

<Link
  to="/forget-password"
  state={formData.email}
>

Check this for docs

CodePudding user response:

With react-router V6 you can use the outlet component and pass a context to another page.

 <Routes>
   <Route path="/login" element={Login}/>
     <Route path="/reset-password" element={ResetPass}/>
</Routes>

const Login = () => {
    ...
    <Outlet context={contextdata} /> // contextdata - data to pass
}


const ResetPass = () => {
    const { contextdata } = useOutletContext<IContext>() // data from Login page

        ...
        <div>{contextdata}</div>
}

Please take a look here: Pass Props to Outlet in React Router v6

  • Related