DEV Community

Sarwar Hossain
Sarwar Hossain

Posted on • Updated on

Pass/navigate full data to any react-router

In React, passing data between components using React Router is a common practice, especially when navigating from one page to another. Let's break down the process of passing and receiving data using React Router with some sample code:

  1. Setting Up Navigation Link: Use the Link component from React Router to create a link to the target page and pass the data through the state object.

Image description



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

<Link
  to={{
    pathname: `/seller/product-management/edit`,
    state: product,
  }}
>
  Details
</Link>



Enter fullscreen mode Exit fullscreen mode

2.Accessing State Data:
Use the useLocation hook to access the state object containing the passed data.

Image description



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

const ProductDetails = () => {
  const { state } = useLocation();

  // Accessing the received data
  const { productName, price, img, status } = state;

  return (
    <div>
      <h2>Product Details</h2>
      <img src={img} alt={productName} />
      <p>Name: {productName}</p>
      <p>Price: {price}</p>
      <p>Status: {status}</p>
    </div>
  );
};

export default ProductDetails;



Enter fullscreen mode Exit fullscreen mode

Top comments (0)