React 'x' is missing in props validation warning (eslint)

72 Views Asked by At

I have tried many combination but could not ix the following error in React app:

'roles' is missing in props validation

Here is related code parts:

const ProRoute = ({ roles = [] }) => {
  const userRoles = service.getCurrentUser()?.roles;
  const isAuthorized = !roles.length || roles.some((r) => userRoles.includes(r));

  // ...
};

export default ProRoute;

and pass roles as shown below:

<Route element={<ProRoute roles={['ROLE_ADMIN']} />}>
  <Route index element={<Student />} />
</Route>

So, what is the cause of the problem? And should I get the roles in curly braces, brackets or etc?

1

There are 1 best solutions below

3
CodeThing On

Like i mentioned in the comments. You need to learn how to use library before using it.

The error above comes because there must be a rule enabled in your eslintrc file called react/prop-types. This basically tells eslint to check for props and their types. This ensures that your components always receives expected props.

To fix the above error you can just add your roles prop in the propTypes object

import PropTypes from 'prop-types';

const ProRoute = ({ roles = [] }) => {
  const userRoles = service.getCurrentUser()?.roles;
  const isAuthorized = !roles.length || roles.some((r) => userRoles.includes(r));

  // ...
};

// Prop validation
ProRoute.propTypes = {
  roles: PropTypes.array
};

export default ProRoute;