Search code examples
javascriptreactjsreact-router-dom

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


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?


Solution

  • 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