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

Viewed 21729

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.

4 Answers

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

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

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.

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

export withRouter(YourComponent)

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

Related