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