How to pass state data in react router dom

#react

Last updated on Nov 10, 2020 by Suraj Sharma



In this tutorial, you will learn how you can pass state data from one route to another in react-router-dom


We can pass data in route using browser's History API, which is possible in React through a custom hook useHistory() 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.


App.jsx

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;


Home.jsx

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



Read the data


To read the data from the location property, you can do something like this


Product.jsx

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



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.