Where to put enums in my react application

11,004

Solution 1

For a more semantic use, you could rename and move your file from config/enum.js to constants/users.js.

There you export each object your want, but with a shortened name: USER_TYPE -> TYPES, USER_STATUS -> STATUS.

So when you import your file you can do: import * as USERS from 'constants/users; and use it like this: USERS.STATUS.FOLLOW.

Solution 2

if I understand correctly what you need.... in one of your file like newfile.js you have to import your enum file like this:

import { USER_TYPES, USER_STATUS,FOLLOWING_STATUS } from './enums'

note: './enums' is a path ... so here you have to put your path

and use as normal constant like this:

USER_TYPES.USER // is it  string  "user",
USER_TYPES.TRAINER // is it  string  "trainer",
USER_TYPES.ADMIN // is it  string  "admin",
USER_STATUS.REQUESTED //is it  string  "Requested",
FOLLOWING_STATUS.FOLLOWING //is it  number 1,
Share:
11,004

Related videos on Youtube

Shashika
Author by

Shashika

Updated on June 04, 2022

Comments

  • Shashika
    Shashika 6 months

    In my react application, I have to use several enums. How should I structure them in my application? What I have done is, I created enums.js file under my config folder, and set enums like this.

    export const USER_TYPES = {
        USER: "user",
        TRAINER: "trainer",
        ADMIN: "admin"
    }
    export const USER_STATUS = {
        FOLLOW: "Follow",
        REQUESTED: "Requested",
        FOLLOWING: "Following"
    }
    export const FOLLOWING_STATUS = {
        FOLLOW: -1,
        REQUESTED: 0,
        FOLLOWING: 1 
    }
    

    Is this a good way of doing this?

  • satchel
    satchel about 1 year
    Do these have to be in a separate file?