skip to Main Content

Currently the constant is defined in the following file

admin/constants/serviceConstants

const FEE_TYPES = {
  flat: "flat",
  perUnit: "per_unit",
};

I have the following components

index.js

List.js

Form.js

Row.js

I need the FEE_TYPES in all the files.

So i am importing this in EACH OF THESE the files as follows.

import { FEE_TYPES } from "admin/constants/serviceConstants";

Rather than importing the constant in ALL the files, Is this the right way or should i go for options such as

  • passing them in the components as props? <List feeTypes={FEE_TYPES} />
  • Defining the constant in the mobx form(I am using mobx form btw) as static variable and using them in the component?

Any help would be appreciated.

3

Answers


  1. Importing is cool to be honest. But if you want to do it:

    There is one way to do it using context. You can read up on that.
    Another way is by adding these values to the global object. Assuming these are React client components, you can run a function once to do this:

    const initAppConstants = () => 
    {
    window.serviceConstants = {
    feeTypes : {
      flat: "flat",
      perUnit: "per_unit",
    },
    courseTypes : 'B'
    };
    }
    
    initAppConstants();
    

    Defining and executing it like above in a file you export in your entry script like index.js will run it only once.
    You can also write the above directly in your index.js.

    Use like this:

    window.serviceConstants.feeTypes
    
    Login or Signup to reply.
  2. If you want an answer, the best way is to import your object in every file you need to use, just import it, you don’t use any props or context for that.

    Login or Signup to reply.
  3. I think it depends on what would you like to do using FEE_TYPES. Normally, we define Constants at constants.js (or something) and import constants for creating clean code or debugging by managing some variables more simple way.

    But, If you use the FEE_TYPES related to business logic or reused at some code, it could be included in Context API or Custom hooks.

    Current example, It seems not bad to import the FEE_TYPES at the all of the components to me.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search