React 18 Router DOM v6 Send or Get Props State with Link Tutorial

Last Updated on by in React JS

React Router is an exceptional package for creating a routing system in React. It allows the user to navigate between different pages via various views and components.

In this extensive tutorial, we will teach you how to pass props object (state) via the Link component in React JS application using React Route DOM v6 package.

On the other hand, we will also ascertain how to get or receive state data from the link component from another component in React JS application.

As we said, it allows navigation between different pages. But React Router is not limited to this. It also allows you to send or pass the props or states through the Link component in React.

A Link is an element of React Router DOM. It allows users to navigate from one page to another by clicking or tapping on the Link element.

In react-router-dom, a Link renders an accessible ahref element that indicates the resource it’s connecting to.

To send the props via the Link in React, we need to pass or set the state in the Link component and also make sure to import it from the react-router-dom library.

Apart from that, we require a useLocation hook. This hook returns the current location object.

It will give us access to perform some side effects whenever the current location changes. We will use useLocation to access or get the props via the link component or props object in React JS.

Set Up React Environment

You must have the development environment set up for React development. Make sure to have Node and Npm installed on your development system.

Once the environment is ready, execute the suggested command to create the new React application.

The following commands will create as well as land you inside the app folder.

npx create-react-app react-blog
cd react-blog

Add React Router v6 Library

Now, type the given command and hit enter to install the router dom library in React.

npm i react-router-dom --legacy-peer-deps

Also, go ahead and install the bootstrap library by running the given command from the console.

npm install bootstrap --legacy-peer-deps

To take the complete advantage of Bootstrap UI components, make sure to add the bootstrap css path in App.js file.

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";

Wrap App Component using BrowserRouter

In the index.js file, you have to import the BrowserRouter API from the “react-router-dom” package and wrap the app component with BrowserRouter api.
.

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>
);

Make New Components

Next, make the new file by the name of components/Profile.js:

import React from "react";

function Profile() {
  return <div>Profile page</div>;
}

export default Profile;

We also need another file, within the components/ folder so create the Dashboard.js file:

import React from "react";

function Dashboard() {
  return <div>Dashboard page</div>;
}

export default Dashboard;

Pass Props Object using Link Component

You have to create the Link components first and then define the props objects with the properties corresponding to send and retrieve through the link component.

Update code in the components/Profile.js file.

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

const Profile = (props) => {
  const profileData = {
    component: "Profile page",
    content: "Data located in profile component",
    timestamp: Date.now(),
  };

  const dashboardData = {
    component: "Dashboard page",
    content: "Data is sent from profile component",
    timestamp: Date.now(),
  };

  return (
    <>
      <div>
        <Link to="/" state={profileData}>
          Go to : Profile
        </Link>
      </div>
      <div>
        <Link to="/dashboard" state={dashboardData}>
          Go to : Dashboard
        </Link>
      </div>
    </>
  );
};

export default Profile;

Retrieve Props or State from Link

We need to use the useLocation api to extract the props or properties that we received via link component.

We can then easily show it in the dashboard component, hence update code in the components/Dashboard.js file.

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

const Dashboard = (props) => {
  const location = useLocation();
  const propsData = location.state;

  console.log(propsData);

  return (
    <>
      <h2 className="mb-4">
        React Send / Get State using Link Component Example
      </h2>
      {propsData && (
        <div>
          <h4 className="mb-3">Data Sent:</h4>
          <p>Page: {propsData.component}</p>
          <p>Content: {propsData.content}</p>
          <p>Timestamp: {propsData.timestamp}</p>
        </div>
      )}
      <hr />
      <Link to="/">Go back to Profile</Link>
    </>
  );
};

export default Dashboard;

Set Up React Routing

To define routes, import the profile and dashboard components.

Additionally, import Route and Routes APIs from the “react-router-dom” package.

Next, define the Route component within the Routes module with route path and element.

In order to enable routing in React with Router DOM, ensure that you add the given code into the App.js component file.

import React from "react";

import "../node_modules/bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

import Profile from "./components/Profile";
import Dashboard from "./components/Dashboard";

import { Route, Routes } from "react-router-dom";

function App() {
  return (
    <div>
      <Routes>
        <Route path="/" element={<Profile />} />
        <Route path="/dashboard" element={<Dashboard />} />
      </Routes>
    </div>
  );
}

export default App;

View App on Browser

It is pretty easy to check the application on the browser, all you have to do is just execute the following command.

npm start

You can test the functionality with given path:

http://localhost:3000

React Router v6 Send or Get Props State with Link Tutorial

Conclusion

So far, we have done with the coding part. That brought us to a stage where we had a complete idea of how to configure routing in React and send data through the link component in React.

And, most importantly, how to receive the values from the passed link component to another component using the useLocation hook.