vivek kn
vivek kn

Reputation: 265

Get url params in ReactJS when using class component

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, "");
   
    };

Upvotes: 5

Views: 21830

Answers (4)

Samuel Mwangi
Samuel Mwangi

Reputation: 11

Okay. I had the same issue and this is how I solved it. I created a separate component with the name getParams.jsx

getParams.jsx

import React from 'react'
import { useParams } from 'react-router-dom'
const getParams = AnyComponent =>props=> {
  return (
    <AnyComponent 
    {...props}
    params={params}>

    </AnyComponent>
  )
}

export default getParams

In now my component where i want to get the parameters, I gave it a different name. In this case, I will use the name of maybe your class based component assuming its name is Student.jsx

Student.jsx

import React, { Component } from 'react'
import getParams from './getParams'
class Student extends Component {
  constructor(props){
    super(props)
  }
  componentDidMount = () => {
//display the id when the component mounts
    console.log(this.props.params.id)
  }
  
  render = () => {
    return (
      <div>
        Student Id is :{this.props.params.id}
      </div>
    )
  }
}
export default getParams(Student)

Upvotes: 0

Ritik Banger
Ritik Banger

Reputation: 2738

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]

Upvotes: 3

Ahmet Firat Keler
Ahmet Firat Keler

Reputation: 4021

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);

Upvotes: 3

crevulus
crevulus

Reputation: 2418

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"

Upvotes: 3

Related Questions