2

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
  • 179
  • 1
  • 4
  • 12

4 Answers4

13

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

Clinton Chau
  • 557
  • 2
  • 12
8

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

nizammoidu
  • 2,074
  • 1
  • 14
  • 14
  • Shouldn't `location` be of type `Location` (as exported from `react-router`) and `params` of type `URLSearchParams`? – romor Dec 19 '21 at 18:03
0

If you are using react-redux, this example will help you. where you are defining your Routes, Use that component as shown:

            <Route path="/user" component={ManageUser} />
            <Route path="/user/:id" component={ManageUser} />

In this ManageUser component, where you are doing mapStateToProps your can use like this:

function mapStateToProps(state, ownProps) {
    const id = ownProps.match.params.id;
   // get the user
    const contextuser = getUserById(state.users, id);
    return {
        contextuser; contextuser
    };
}

In this way you can pass the User to your component.

KushalSeth
  • 3,265
  • 1
  • 26
  • 29
-2

import { withRouter } from 'react-router-dom'

export withRouter(YourComponent)

then access this.props.match.params in your component

Red Baron
  • 7,181
  • 10
  • 39
  • 86