I’m passing getting slug as anchor tag ‘href’ and passing it as URl param to make an API call. Page is correctly routing and get change as per slug. However, I’m not getting slug as props parameter.
-
Here ProductListPage is successfully get render
function App() { return ( <Router> <Routes> <Route path="/" exect element={<Homepage />} /> <Route path="/:slug" element={<ProductListPage />} /> </Routes> </Router> ); } export default App;
-In this ProductList page to make an API call I’m not getting that slug as param
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { getProductBySlug } from "../../actions";
import Layout from "../../Components/Layout/Layout";
const ProductListPage = (props) => {
const dispatch = useDispatch();
useEffect(() => {
console.log(props);
// dispatch(getProductBySlug(props.match.params.slug));
}, [dispatch]);
return <Layout>ProductListPage</Layout>;
};
export default ProductListPage;
>Solution :
You’re probably just missing the useParams() hook call.
Here’s how to implement it into your ProductList file:
import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import { getProductBySlug } from "../../actions";
import Layout from "../../Components/Layout/Layout";
import { useParams } from 'react-router-dom'; // importing the hook
const ProductListPage = (props) => {
const dispatch = useDispatch();
let params = useParams(); // calling the hook
useEffect(() => {
console.log(props);
dispatch(getProductBySlug(params.slug)); // you'll be able to use params object this way now (omitting the 'prop.match' prefix).
}, [dispatch]);
return <Layout>ProductListPage</Layout>;
};
export default ProductListPage;
The React Router documentation regarding the useParams hook: https://v5.reactrouter.com/web/api/Hooks/useparams