How to get parameter value from react-router-dom v6 in class

16,377

Solution 1

The library-provided HOC, withRouter, has been deprecated in React Router v6. If you need to use v6 and are using class-based React components, then you will need to write your own HOC which wraps the v6 use* hooks.

For example:

export function withRouter( Child ) {
  return ( props ) => {
    const location = useLocation();
    const navigate = useNavigate();
    return <Child { ...props } navigate={ navigate } location={ location } />;
  }
}

This is useful if you have a large code base that you need to move to v6, but haven't migrated all of your class-based components into functional ones.

This is based on the recommendation from the dev team as stated in this Github issue: https://github.com/ReactTraining/react-router/issues/7256 t

Solution 2

Typescript HoC

import React from "react";
import { NavigateFunction, useLocation, useNavigate, useParams } from "react-router";

export interface RoutedProps<Params = any, State = any> {
    location: State;
    navigate: NavigateFunction;
    params: Params;
}


export function withRouter<P extends RoutedProps>( Child: React.ComponentClass<P> ) {
    return ( props: Omit<P, keyof RoutedProps> ) => {
        const location = useLocation();
        const navigate = useNavigate();
        const params = useParams();
        return <Child { ...props as P } navigate={ navigate } location={ location } params={ params }/>;
    }
}

then let the class component props extends RoutedProps with optional Params and State types

Share:
16,377

Related videos on Youtube

An Dương
Author by

An Dương

Updated on June 04, 2022

Comments

  • An Dương
    An Dương almost 2 years

    I'm using react-router-dom v6 and don't know how to get parameter value

    ex: http://localhost:3000/user/:id

    i want to get :id

    Someone use hook useParams to get but i'm using class so i can't use hook.

  • An Dương
    An Dương almost 4 years
    i'm using react-router-dom v6 and withRouter is not available: 'withRouter' is not exported from 'react-router-dom'
  • Red Baron
    Red Baron almost 4 years
    @AnDương is there a reason you need to use v6?
  • An Dương
    An Dương almost 4 years
    yes, it is very light and have Outlet is very useful
  • Red Baron
    Red Baron almost 4 years
    and the reason you can't use a functional component?
  • romor
    romor over 2 years
    Shouldn't location be of type Location (as exported from react-router) and params of type URLSearchParams?