Home > Software engineering >  How to get match path in react new version
How to get match path in react new version

Time:05-04

What I am trying to achieve is to get the path of the url using match in order to display the shop category.

The issue I am having is that match is undefined even when i did console.log(match), it is still showing undefined.

If I should console.log(match) alone then the page will display the components very well but the match will be undefined from the console but when I include as it is being used in the tutorial the entire page will go blank and the match will still be undefined.

Please can anyone help me out. I have tried all I can.

Below is the shop.components.jsx


import React from "react";
import {BrowserRouter as Router, Route, Routes  } from 'react-router-dom';
import CollectionsOverview from "../../components/collections-overview/collections-overview.components";

const ShopPage = ({ match }) => {
    console.log(match);
    return(
        <div className="shop-page">
            <Route path={`${match.path}`} element={<CollectionsOverview/>} />
        </div>

)};

export default ShopPage;

CodePudding user response:

To get match path in react new version, you should use "useLocation" from react

import React, { useLocation } from "react";
import {BrowserRouter as Router, Route, Routes  } from 'react-router-dom';
import CollectionsOverview from "../../components/collections-overview/collections-overview.components";

const ShopPage = () => {
    const { pathname } = useLocation()
    console.log(pathname);

    // you can replace all path with "*" e.g path="*" which is commonly used for notfound page
    return(
        <div className="shop-page">
            <Route path={`${match.path}`} element={<CollectionsOverview/>} />
        </div>

)};

export default ShopPage;

CodePudding user response:

In react-router-dom@6 there are no longer any route props (i.e. history, location, and match), so match, as a prop, is undefined. From what I can tell you are trying to build a nested route similar to how it's done in RRDv5. RRDv6 builds nested routes and links relative to the parent Routes component, so it's unnecessary to attempt to "build" the route here, you can simply use path="/" for the route and it will be relative from the Routes component rendering the route for ShopPage.

Example:

const ShopPage = () => {
  return (
    <div className="shop-page">
      <Routes>
        <Route path="/" element={<CollectionsOverview/>} />
      </Routes>
    </div>
  );
};

If ShopPage component is rendered on path "/app/shopping/page", then CollectionsOverview will be also rendered on "/app/shopping/page".

  • Related