Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling parameters passed through react-router in component

So, in react-router v4, my Route looks like this:

      <Route path="/suppliers/:id?" component={Suppliers} />

I'm passing an optional 'id' parameter to my Suppliers component. This is no problem.

For posterity, this is my Link: <Link to="/suppliers/123">Place Order</Link>

Then, in my component, I refer to the parameter as such: <p>{this.props.match.params.id}</p>

This works, but my linter gives me the following error: [eslint] 'match' is missing in props validation (react/prop-types)

For this reason, I've defined the propTypes as such:

Suppliers.propTypes = {
  match: PropTypes.shape({
    params: PropTypes.shape({
      id: PropTypes.number,
    }).isRequired,
  }).isRequired,
};

But it feels like I'm writing more boilerplate code than I probably require. My question is, Is there a better way to define my propTypes in my component so as to avoid the linter error? Also, this solution seems unsustainable if, for instance, the props.match property changes it will break. Or am I doing this correctly?

Thanks in advance.

like image 786
S.V. Avatar asked Sep 07 '17 08:09

S.V.


People also ask

How does react router handle parameters in URL?

Using React Router, when you want to create a Route that uses a URL parameter, you do so by including a : in front of the value you pass to Route 's path prop. Finally, to access the value of the URL parameter from inside of the component that is rendered by React Router, you can use React Router's useParams Hook.

How do you pass data using router navigate in react?

To pass data when navigating programmatically with React Router, we can call navigate with an object. Then we can use the useLocation hook to return the object's data. const navigate = useNavigate(); navigate('/other-page', { state: { id: 7, color: 'green' } });


1 Answers

Your code is okay but you can also define the proptypes as object.

match: PropTypes.object.isRequired

If one day you need other props such match, location, history. you can define it this way.

Suppliers.propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }
like image 117
Hana Alaydrus Avatar answered Sep 22 '22 16:09

Hana Alaydrus