9

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?

JS3
  • 1,623
  • 3
  • 23
  • 52

1 Answers1

26

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

import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';

export function withRouter<ComponentProps>(Component: React.FunctionComponent<ComponentProps>) {
    function ComponentWithRouterProp(props: ComponentProps) {
        const location = useLocation();
        const navigate = useNavigate();
        const params = useParams();

        return <Component {...props} router={{ location, navigate, params }} />;
    }

    return ComponentWithRouterProp;
}

For more details check this out

Gil Epshtain
  • 8,670
  • 7
  • 63
  • 89
Sanket Shah
  • 2,888
  • 1
  • 11
  • 22
  • 2
    Just finished implementing it and it works. Thank you – JS3 Feb 13 '22 at 05:22
  • 1
    If I use this `withRouter` to wrap a component, is it possible to access `history` in that component? I am having trouble trying to execute `history.push('/')` inside the component, because `history` is undefined. – S.Ale Aug 12 '22 at 06:20
  • 1
    You need to use `useNavigate` instead of `useHistory`. [Reference](https://reactrouter.com/docs/en/v6/upgrading/v5#use-usenavigate-instead-of-usehistory) – Sanket Shah Aug 12 '22 at 11:40