How to pass a variable when routing in react router v6?

How to pass a variable when routing in react router v6?

An Introduction to React Router Version 6

ยท

2 min read

Usually, when using a backend such as Node Js, we can easily pass variables from the server. But when using React, a front-end framework, how is data passed from one route to another?

Setup

First, we will setup our index.js file in the source folder in our react project

import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <Router>
        <Routes>
            <Route path="/*" element={<App />} />
        </Routes>
    </Router>
);

So now every route will be navigated to the App component.

Here is our setup for the App component:

import { Routes, Route } from "react-router-dom";
import Home from "./components/Home";
import About from "./components/About";

function App() {
    return (
        <>
        <Routes>
            <Route exact path="/" element={<Home />}></Route>
            <Route exact path="/about" element={<About />}></Route>
        </Routes>
        </>
    );
}

export default App;

Sending data

Say when we navigate from the home page to the about page, we want to send some data. Here is the implementation

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

function Home() {
    return (
        <>
        <Link to='/about' state={{ data: "foo" }}>About page</Link>
        </>
    );
}

export default Home;

The data property is sent to the about route with value "foo" using the state property

Accessing the data

The useLocation hook can be used to access data sent from the link

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

function About(){
    const location = useLocation();
    return (
        <>
        <h1>{location.state.data}</h1>
        </>
    );
}

Conclusion

That is it from this blog! Thank you for reading and happy coding!

ย