Reputation: 3197
I have a react component which is loaded on routing
I need to access a parameter from the url inside the components constructor
How do I do it?
can I access it like this:
class CustomCoponent extends React.Component {
constructor(props,{match}) {
}
}
Upvotes: 11
Views: 36822
Reputation: 1041
Routes
import logo from './logo.svg';
import './App.css';
import {BrowserRouter as Router,Route,Switch} from 'react-router-dom';
import UpdateEmployeeComponent from './components/UpdateEmployeeComponent';
function App() {
return (
<div>
<Router>
<div className="container">
<Switch>
<Route path="/update-employee/:id" component={UpdateEmployeeComponent}></Route>
</Switch>
</div>
</Router>
</div>
);
}
export default App;
Component
import React, { Component } from 'react';
class UpdateEmployeeComponent extends Component {
constructor(props){
super(props);
this.state ={
id : this.props.match.params.id
}
console.log('Employee Id ::: '+this.id);
}
render() {
return (
<div>
</div>
);
}
}
export default UpdateEmployeeComponent;
Upvotes: 0
Reputation: 2869
if you use routing then you can specify your route to expect the parameter.
<Route path='/yourpath/:ParamName' component={CustomComponent}/>
your component needs to be wrapped in the withRouter HOC for you to access this.
import {withRouter} from 'react-router-dom';
class CustomComponent extends React.Component{
constructor(props){
}
//**ACCESS PARAMETER VALUE LIKE THIS**
sample(){
let Paramvalue=this.props.match.params.ParamName;
}
}
export default withRouter(CustomComponent);
Upvotes: 7
Reputation: 9
As {match} is passed to the component as a prop(property) so we can access this prop as a normal prop way.
class CustomComponent extends React.Component {
console.log(this.props.match.url)
}
Upvotes: 0
Reputation: 3091
You can do it like this:
class CustomComponent extends React.Component {
constructor({ match, ...props }) {
console.log(match.params)
}
}
Upvotes: 4
Reputation: 3932
You can access route parameter in react-router-dom
v4.x
, by getting params from the match
props.
Where you define your routes,
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
...
<Router>
<App>
<Switch>
<Route exact path="/" component={List} />
<Route path="/:parameterToAccess" component={CustomComponent} />
</Switch>
</App>
</Router>
...
In your component,
class CustomComponent extends React.Component {
constructor(props) {
super(props);
this.routeParam = props.match.params.parameterToAccess;
}
}
Upvotes: 10