How to share props using navigation Link in React

How to share props using navigation Link in React

Hi, have you been in a situation where you need to share data between two non-nested pages/components and you really don't want to move the data to the global state? Good news! You can easily share the data using the Link component that comes with react-router-dom. Sounds cool? Let's try it out!

// First Page
const Page1 = ( ) => {
  const [user, setUser] = useState({email: "test@gmail.com", password: 1234 });

 return (
       <Link to={{ pathname: '/page2', state: { user } }}>
           To Next Page
       </Link>
   )
}

On Page1 component, we have the user object in the state which contains the user's email and password and it's passed as a prop to the to attribute of Link as an object, specifying the path and the state.

To get the user details on the second page, you can get that from the props just like this:

// Second Page
const Page2 = (props) => {
 const user = props.location.state.user; 
//OR
 const { user } = props.location.state; // object destructuring

 return (
       <>
           { user ? `Signed in as ${user.email}` : "Not Signed in!" }}
       </>
   )
}

We get the user's details from location object which is nested inside the props. So, if the user is truthy, we display Signed in as 'email' or Not signed in! if there is no item in the user object falsy.

That's it. I hope that helps you in avoiding moving data to the global state whenever you need to share data between two non-nested pages/components.

Is there a better approach to this? Drop your thoughts in the comment section below.

Till next time, have a nice day!