I have the following config in App.jsx
<Route path='/Main' component={Main} />
<Route path='/Details' component={Details} />
So when a user selects the Details , they will be taken to the Detaiuls page. But I want to pass a few parameters and their values from the main page
How can i do that ?
>Solution :
In order to pass data between React pages, you can use the React Router library to navigate to different routes and pass parameters as part of the route’s URL.
import React from "react";
import { useHistory } from "react-router-dom";
const Main = () => {
const history = useHistory();
const handleNavigateToDetails = () => {
// Pass parameters as part of the URL
history.push("/Details?param1=value1¶m2=value2");
};
return (
<div>
<h1>Main Page</h1>
<button onClick={handleNavigateToDetails}>Go to Details</button>
</div>
);
};
export default Main;
In this component, as you can see, when you click the "Go to Details" button, the handleNavigateToDetails function is called, which uses history.push to navigate to the /Details route with the parameters param1=value1 and param2=value2 included in the URL.
import React from "react";
import { useLocation } from "react-router-dom";
const Details = () => {
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
// Access the parameter values
const param1 = searchParams.get("param1");
const param2 = searchParams.get("param2");
return (
<div>
<h1>Details Page</h1>
<p>Param 1: {param1}</p>
<p>Param 2: {param2}</p>
</div>
);
};
export default Details;
In this Details component, the useLocation hook is used to access the current location object.
The search property of the location object contains the query parameters from the URL. We can parse these parameters using the URLSearchParams API.
When the user navigates from the Main page to the Details page, the parameters param1 and param2 will be passed in the URL, and the Details component can access and utilize those parameter values.