Home > database >  Wrap withRouter in an ES7 function
Wrap withRouter in an ES7 function

Time:11-03

I have a DetailProducts function, how can I wrap DetailProducts in withRouter. Thanks

import React from "react";
import details from "../../CSS/ProductsCss/details.css";
import { withRouter } from "react-router-dom";

export default function DetailProducts() {
  return (
    <div className="single-product">
      
    </div>
  );
}

CodePudding user response:

Put the react-router-dom's Provider on the ancestor of this component

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";
import App from "./App";

// for example I put it in the really beginning of the app
// you may change the placement of <Router />
ReactDOM.render(
  <StrictMode>
    <Router>
      <App />
    </Router>
  </StrictMode>,
document.getElementById("root")
);

Then wrap you component inside withRouter HOC

import React from "react";
import details from "../../CSS/ProductsCss/details.css";
import { withRouter } from "react-router-dom";

function DetailProducts(props) {
  // you have access to following and even more things
  const { match, location, history } = props;

  return (
    <div className="single-product">
      
    </div>
  );
}

export default withRouter(DetailProducts)

Migration:

as version 5 suggest you should update your component to use the hook version instead.

Replace all uses of withRouter with hooks. Upgrade to v5.1

Replace any withRouter usage with hooks. They give you access to all the same stuff. Again, although withRouter is not deprecated in 5.1, it's a weird API when you can compose your state with hooks instead. It will also most likely be deprecated in a future release. post

Here is a list of available hooks which are pretty clear by their name, but if you want to dig into them. check the Hook api section in the doc

  • useHistory
  • useLocation
  • useParams
  • useRouteMatch

CodePudding user response:

Hooks are the preferred method now. It might look something like this:

import { useHistory } from "react-router-dom";

export default function DetailProducts() {
  const history = useHistory();

  function handleClick() {
    history.push("/some-path");
  }

  return (
    <div className="single-product">
      <button onClick={handleClick}>Click this</button>
    </div>
  );
}

Check the docs for the other useful hooks which provide coverage of the other functionality from withRouter.

  • Related