Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access url parameter in a react component

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}) {
    }
}
like image 998
Rahul Yadav Avatar asked Mar 01 '18 09:03

Rahul Yadav


People also ask

How do you get the URL params in React JS class component?

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 .

How do I find the URL route in React?

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 .


1 Answers

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);
like image 136
Sujit.Warrier Avatar answered Oct 05 '22 19:10

Sujit.Warrier