Hello guys, in this article, we will explain to you how to get url params in class component with example in react. we will give you a simple example of how to get url params in class component into the react.
import { Container } from 'react-bootstrap';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Product from './components/Product'
function App() {
return (
<Router>
<Header />
<main className="py-3">
<Container>
<Routes>
<Route path='/product/:id' element={<Product/>} />
</Routes>
</Container>
</main>
<Footer />
</Router>
);
}
export default App;
import React, { Component } from 'react';
class Product extends Component {
constructor(props) {
super(props);
}
componentDidMount () {
const productId = this.props.match.params.id;
console.log(productId); //get product id
}
render() {
const { id } = this.props.match.params;
return (
<div><p>ProductId: { id }</p></div>
);
}
}
export default Product;