If you accidentally installed react-router-dom
v6 then the withRouter
HOC no longer exists. Either revert back to v5 (run npm install -s react-router-dom@5
), or roll your own custom withRouter
HOC to inject the props you need or convert the components to function components and use the React hooks.
Create custom withRouter
Higher Order Component
From the FAQ: What happened to withRouter I need it
import { useLocation, useNavigate, useParams, } from "react-router-dom"; function withRouter(Component) { function ComponentWithRouterProp(props) { let location = useLocation(); let navigate = useNavigate(); let params = useParams(); return ( <Component {...props} router={{ location, navigate, params }} /> ); } return ComponentWithRouterProp; }
Convert to function component
There is now also no longer a history
object to use, it was replaced by a navigate
function accessed via the useNavigate
hook. It’s not clear where history
was being used previously, but if you need to imperatively navigate the following is how you access the navigation. If staying with v6 then the following is how to access the navigate
function.
import React from 'react';
import { useNavigate } from 'react-router-dom';
import './menu-item.scss';
const MenuItem = ({ title, imageUrl, size }) => {
const navigate = useNavigate();
// navigate("/targetPath")
return (
<div className={`${size} menu-item`}>
<div
className="background-image"
style={{
backgroundImage: `url(${imageUrl})`,
}}
/>
<div className="content">
<h1 className="title">{title.toUpperCase()}</h1>
<span className="subtitle">SHOP NOW</span>
</div>
</div>
)
};
export default MenuItem;