React Pass / Get Props State via Link with Router Dom v6 Tutorial

React Router DOM v6 pass / get state using links example. Passing data from one component to another component is a common task. Generally, data is passed through props which are used to update the state in React.

Do you know there is another way through which data is passed using the Link component in React?

In this detailed guide, you will learn how to send props (state data) through Links in React js using React route dom version 6 library. Not only but also show you how to retrieve props data from links in React using router dom APIs.

Router DOM and React go hand in hand; router dom is a library that is used to set up or enable routing in React.

To pass data through the Links, we will use React Router 6 package. Not just that, we will also profoundly teach you how to get the passed data in React component that we passed through react-router links.

We will show you everything from absolute scratch. We’ll start with creating a basic React app, and to pass the state via the Link component, we will use React hooks in the functional component.

Create React App

If you haven’t created the React project yet, go ahead and run the suggested command:

npx create-react-app my-react-app

Jump to the subsequent step, if already done.

Step inside the project directory:

cd my-react-app

Install Router DOM v6 Package

Here in this step, we will do the most important thing. That is to add the router dom library to React; for that execute the given command.

npm install react-router-dom

To get rid from writing custom CSS; we are installing bootstrap library with given code.

npm install bootstrap

Add BrowserRouter Component

To make the react-router available throughout React app, open and add the given code to the src/index.js file.

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";

import { BrowserRouter } from "react-router-dom";

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

Create Component Files

Inside the src/ folder, you have to make the features/ folder:

Then, make the Products.js file using following code:

import React from 'react'

function Products() {
  return (
    <div>Products page</div>
  )
}

export default Products

Next, create the UserProfile.js file using suggested code:

import React from 'react'

function UserProfile() {
  return (
    <div>User profile page</div>
  )
}

export default UserProfile

Pass Props Data through Link

In order to send the props via Link component, make sure to insert the code into the features/Products.js file and paste the following code into the file.

import { Link } from "react-router-dom";

const Products = (props) => {
  const productsData = {
    page: "Products",
    data: "Data is coming from products page",
    timestamp: Date.now(),
  };

  const userProfileData = {
    page: "User Profile",
    data: "Data is coming from user profile page",
    timestamp: Date.now(),
  };

  return (
    <>
      <h2 className="mb-5">React Pass and Get Props via Link API Example</h2>
      <p>
        <Link to="/" state={productsData}>
          Navigate to : Products
        </Link>
      </p>
      <p>
        <Link to="/user-profile" state={userProfileData}>
          Navigate to : User Profile
        </Link>
      </p>
    </>
  );
};

export default Products;

Get State from Link Component

We require useLocation API to retrieve the props through Link. The useLocation Returns the current location object, which represents the current URL in web browsers.

Thus, place the code into the features/UserProfile.js file.

import { Link, useLocation } from "react-router-dom";

const UserProfile = (props) => {
  const loc = useLocation();
  const propsState = loc.state;

  console.log(propsState);

  return (
    <>
      <h2 className="mb-3">User Profile Page</h2>
      {propsState && (
        <div>
          <h4 className="mb-3">Passed data:</h4>
          <p>Page: {propsState.page}</p>
          <p>Data: {propsState.data}</p>
          <p>Timestamp: {propsState.timestamp}</p>
        </div>
      )}
      <hr />
      <Link to="/">Go Products</Link>
    </>
  );
};

export default UserProfile;

Update App.js File

Now, we have to open the src/App.js file and insert the code into the file.

import React from "react";
import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import { Routes, Route } from "react-router-dom";
import Products from "./features/Products";
import UserProfile from "./features/UserProfile";

function App() {
  return (
    <div className="container mt-5">
      <Routes>
        <Route path="/" element={<Products />} />
        <Route path="/user-profile" element={<UserProfile />} />
      </Routes>
    </div>
  );
}

export default App;

Run React Server

To run the React application, make sure to run the suggested command.

npm start

React Pass / Get Props State via Link with Router Dom v6 Tutorial

Conclusion

We have learned how to set up and use react-router-dom v6 in our React app. In this tutorial, we highlighted all the essential steps to pass data between pages in React via Link component.

We have also seen how to retrieve data from the Link component passed via Links in React project.

We hope you liked this guide. This guide will surely solve your problem and help your endeavours to enhance your React skills.