Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Router – passing Slug as a prop to child Component and not getting params of url

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading