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.
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.
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' } });
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
}
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