Home > database >  is there an alternative of withRouter from react-router
is there an alternative of withRouter from react-router

Time:06-24

I am trying to access match prop from a child component but I cant since I see it is no longer supported. Is there an alternative to this or is there another way I can access these parameters from child component without tunneling or downgrading react-router?

import React from "react";
import './menuItem.style.scss'
import { withRouter } from "react-router";

const MenuItem = ({title, imageUrl,size,linkUrl, match}) => (
    // console.log(match),
    <div className={`${size} menu-item`} onClick={ ()=> window.history.push(`${match.url}${linkUrl}`)}>
        <div style={{backgroundImage: `url(${imageUrl})`}}  className="background-image" ></div>
        <div className="content">
            <h1 className="title">{title.toUpperCase()}</h1>
            <span className="subtitle">Shop Now</span>
        </div>
    </div>
);
export default withRouter(MenuItem);

CodePudding user response:

It seems you are asking how to access the currently matched url in react-router@6. V6 doesn't export a withRouter HOC, but since you are using a React function component you don't need it since it can import and use the RRD React hooks.

RRDv6 also doesn't need to know the full matched URL as it can navigate using relative paths. The difference between relative and absolute paths is a leading "/" character. Target paths starting with "/" are treated as absolute paths, and without are treated as relative paths.

You can import the useNavigate hook and issue a relative navigation from the current location.

Example:

import React from "react";
import './menuItem.style.scss';
import { useNavigate } from "react-router";

const MenuItem = ({ title, imageUrl, size, linkUrl }) => {
  const navigate = useNavigate();

  return (
    <div
      className={`${size} menu-item`}
      onClick={() => navigate(linkUrl)}
    >
      <div
        style={{ backgroundImage: `url(${imageUrl})` }}
        className="background-image"
      />
      <div className="content">
        <h1 className="title">{title.toUpperCase()}</h1>
        <span className="subtitle">Shop Now</span>
      </div>
    </div>
  );
};

export default MenuItem;

If you are still using class components that need access to the old "route props" then you'll need to roll your own withRouter HOC.

Example:

import { useParams, /* ...other hooks */ } from 'react-router-dom';

const withRouter = WrappedComponent => props => {
  const params = useParams();
  // ...other hooks

  return (
    <WrappedComponent
      {...props}
      {...{ params, /* other hook props */ }}
    />
  );
};

export default withRouter;
  • Related