Last updated on Jun 15, 2021 by Suraj Sharma
In this tutorial, you will learn how you can pass state data from one route to another using the react-router-dom
library
We can pass data in route using browser's History API, which is possible in React through a custom hook useHistory()
available in react-router-dom
Consider we have a <Home />
component, on click of a button we want to get redirected to a '/product'
route and pass a product details along with the route,
later display the product details on the product page or simply the <Product />
component.
import React from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Home from './Home';
import Product from './Product';
const App = () => {
return (
<BrowserRouter>
<Switch>
<Route path="/home" component={Home} />
<Route path="/product" component={Product} />
</Switch>
</BrowserRouter>
)
};
export default App;
import React from 'react';
import { useHistory } from 'react-router-dom';
const products = [
{id: '1', name: 'Phone', price: '$399'},
{id: '2', name: 'television', price: '$299'}
]
const Home = () => {
const history = useHistory();
const handleClick = (data) => {
history.push({
pathname: '/product',
state: data
});
}
return (
<ul>
{products.map(product=>(
<li
key={product.id}
onClick={()=>handleClick(product)}
>
{product.name}
</li>
))
</ul>
)
}
export default Home;
To solve this problem, we have used useHistory()
hook
useHistory()
returns a history
object and to the history object we push the new object, which comprises the pathname
and the state
object.
The data pass through to the product route is available in the <Product />
component props, inside the location property
To read the data from the location
property, you can do something like this
import React from 'react';
const Product = (props) => {
const productDetails = props.location.state || {};
// state object contains the data
return (
<div>
<span>{productDetails.id}</span>
<span>{productDetails.name}</span>
<span>{productDetails.price}</span>
</div>
);
}
export default Product;
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.