Search code examples
javascriptreactjsreact-proptypes

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


Solution

  • 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.