Home > Software engineering >  useParam is not working in react router Dom v6?
useParam is not working in react router Dom v6?

Time:09-07

I am trying to pass a parameter to my other component which is productDetail component but when I am trying to access that parameter value using useParam it doesn't seems to work:

App:

import React from "react";
import { Route, Routes } from "react-router-dom";
import MainHeader from "./components/MainHeader.jsx";
import Product from "./pages/Product.jsx";
import ProductDetails from "./pages/ProductDetails.jsx";
import Welcome from "./pages/Welcome.jsx";

const App = () => {
  return (
    <div style={{ textAlign: "center" }}>
      <header>
        <MainHeader />
      </header>
      <Routes>
        <Route path="/welcome" element={<Welcome />} />
        <Route path="/product" element={<Product />} />
        <Route path="/products/:productId" element={<ProductDetails />} />
      </Routes>
    </div>
  );
};

export default App;

ProductDetailes:

import React from "react";
import { useParams } from "react-router-dom";

const ProductDetails = () => {
  const params = useParams;
  console.log(params.productId);

  return (
    <div>
      <h1>Product Detail</h1>
      <p>{params.productId}</p>
    </div>
  );
};

export default ProductDetails;

CodePudding user response:

The useParams hook is a function and actually needs to be invoked in order to have any effect.

Example:

const ProductDetails = () => {
  const { productId } = useParams();

  useEffect(() => {
    console.log({ productId });
  }, [productId]);

  return (
    <div>
      <h1>Product Detail</h1>
      <p>{productId}</p>
    </div>
  );
};
  • Related