Iorweth333
Iorweth333

Reputation: 512

How to use imported values in React PropTypes?

I'm creating PropTypes for a functional component and I want to use PropTypes.oneOf with an object imported from another file:

import { MODES } from '../../../Users';
(...)
ManageUserForm.propTypes = {
    mode: PropTypes.oneOf(Object.values(MODES)),
}

In Users.js, MODES looks like this:

export const MODES = {
    add: 'add', edit: 'edit', changePassword: 'changePassword',
    block: 'block', unblock: 'unblock', delete: 'delete'
};

But I get an error stating that MODES is undefined. For now, I solved it by just hardcoding the values, but that's inelegant and I want to improve it. What can I do?

EDIT: I recreated the problem in a sandbox: codesandbox.io

Upvotes: 0

Views: 136

Answers (2)

Egor Koldasov
Egor Koldasov

Reputation: 41

You have a circular dependency.

  1. First the code imports Users.js from App.js.
  2. Then Users.js imports UserCreator.js.
  3. Then UserCreator.js imports ManageUserForm.js.
  4. Then ManageUserForm.js imports Users.js again

All this even before MODES variable is being defined. You should not import Users.js in ManageUserForm.js since Users.js itself depends on ManageUserForm.js through UserCreator.js.

You can move MODES definition to ManageUserForm.js and import it in Users.js or better move it to a separate file completely.

Upvotes: 1

Muhammad Haseeb
Muhammad Haseeb

Reputation: 1341

This would work but I will recommend to keep it in the same file because it was not imported when it defines the proptypes.

ManageUserForm.propTypes = {
  mode: PropTypes.oneOf(Object.values(require('../../../Users'))),
}

Here is a codeSandbox example https://codesandbox.io/s/react-example-forked-y1br4?file=/index.js

Upvotes: 1

Related Questions