Match a _route_ to a component with React Router and that component will have certain props. location is one of these props but when it is used in a component, ESLint can throw an error...
e.g. 'location' is missing in props validation.
Given the follow code, what am I doing/not doing to provoke the above error and what should I do about it?
root.js:
import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import Frame from './components/frame';
import NotFound from './components/notFound';
render((
<BrowserRouter>
<Switch>
<Route exact path="/" component={Frame} />
<Route component={NotFound} />
</Switch>
</BrowserRouter>
), document.querySelector('#root'));
notFound.js:
import React from 'react';
const NotFound = ({ location }) => (
<div>
<p>Sorry but <b>{location.pathname}</b> didn鈥檛 match any pages</p>
</div>
);
export default NotFound;
Thanks
I can add the following to notFound.js but that doesn't seem accurate, and I wonder if there is a more global way to do it and associate it with React Router.
NotFound.propTypes = {
location: React.PropTypes.string.isRequired,
};
That is entirely accurate - if NotFound expects a prop, it should be defining that prop in propTypes.
react-router may provide propType definitions for it already, but whether they do or not, you'd still need to explicitly connect them.
Thanks @ljharb for the reply. It was the string part that felt _inaccurate_ and object provokes a forbid-prop-type error.
I've found a way to satisfy ESLint problems and describe the props that the component expects:
NotFound.propTypes = {
location: React.PropTypes.shape({
pathname: React.PropTypes.string.isRequired,
}),
};
NotFound.defaultProps = {
location: {
pathname: '',
},
};
That sounds like a much better propType :-)
@LL782 what about
NotFound.propTypes = {
location: React.PropTypes.shape({
pathname: React.PropTypes.string.isRequired,
}).isRequired,
};
thank you @dougbacelar
React.PropTypes is deprecated since React 15.5.0, use the npm module prop-types instead;
import PropTypes from "prop-types";
NotFound.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
};
Thanks @ljharb for the reply. It was the
stringpart that felt _inaccurate_ andobjectprovokes aforbid-prop-typeerror.I've found a way to satisfy ESLint problems and describe the props that the component expects:
NotFound.propTypes = { location: React.PropTypes.shape({ pathname: React.PropTypes.string.isRequired, }), };
Thank you sir!
Most helpful comment
@LL782 what about