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}) {
}
}
To get the url parameter from a current route, we can use the useParams() hook in react router v5. Consider, we have a route like this in our react app. Now, we can access the :id param value from a Users component using the useParams() hook. In React router v4, you can access it using the props.match.params.id .
Use the useLocation() hook to get the current route with React Router, e.g. const location = useLocation() . The hook returns the current location object. For example, you can access the pathname as location. pathname .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With