Get url params in ReactJS when using class component

Viewed 3805

This is my URL in react js

http://localhost:3000/meassger/student/1

I want to extract 1 from the URL if it was a functional component I could have used ```useParams``

I am getting this error TypeError: Cannot read properties of undefined (reading 'params')

 componentDidMount() {
    console.log(this.props.match.params.id, "");
   
    };
3 Answers

In functional component, use

const history = useHistory()

const studentId = history?.location?.pathname.split('/')[3]

In class component, use

const studentId = window.location.href.split('/')[3]

You need to wrap it in withRouter - that injects the URL variables into your props.

You can find an example here: https://stackoverflow.com/a/60316195/13063136

The code:

import React from "react";
import { withRouter } from "react-router";

class ShowTheID extends React.Component {

  const { match } = this.props;

  componentDidMount() {
    console.log(match.params.id)
  }

  render() {
    return <div>{match.params.id}</div>;
  }
}

const ShowTheIDWithRouter = withRouter(ShowTheID);

Note: Along with wrapping your component in withRouter you also need to make sure that your route is registered and you have mentioned URL params in your Route path like path="/meassger/student/:id"

Let's assume we have a url like http://localhost:3000/student/:studentId and we need to grab studentId param from this url

In a functional component, we can do it like

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

const Student = () => {
    const { studentId } = useParams();
    return (
        <div>StudentId: { studentId }</div>
    );
}
export default Student;

In a class based component, we can do it like

import React, { Component } from 'react';

class Student extends Component {
    render() {
        const { studentId } = this.props.match.params;
        return (
            <div>StudentId: { studentId }</div>
        );
    }
}
export default Student;

Alternatively, you can use withRouter HOC. By doing so, you can also access location and history props.

import React, { Component } from 'react';
import { withRouter } from "react-router";

class Student extends Component {
  render() {
    const { location, history } = this.props;

    return (
      <React.Fragment>
        <div>StudentId: { match.studentId }</div>
        <div>Path: {location.pathname}</div>
      </React.Fragment>
    );
  }
}

const StudentWithRouter = withRouter(Student);
Related