How can I use withRouter in react router v6 for passing props?

Viewed 8772

Before, you would need to wrap something like this export default withRouter(name of component) and now it is different in react-router v6.

I have this button where once you clicked this, it will take you to another page including the value inside my tableMeta.rowData[0]. I tried using navigate = useNavigate(), but I do not know how to pass the value of tableMeta.rowData[0]

   {
      name: "Edit",
      options: {
        customBodyRender: (value, tableMeta, updateValue) => {
          return (
            <Button
              color="success"
               onClick={
            () => navigate("/edit-products")
            // console.log(tableMeta.rowData[0])
          }
            >
              Edit
            </Button>
          );
        },
      },
    },

In React-router v6, how can I do this similar to a withRouter before?

1 Answers

It is deprecated. You can recreate it using the hooks version:

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;
}

For more details check this out

Related