Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put enums in my react application

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?

like image 615
Shashika Avatar asked Jan 30 '19 09:01

Shashika


People also ask

How do you use enums in Reactjs?

In the App. js file, we will create an enum object first. After that, we will add an 'enum' function to render components according to state value. At last, we will edit the 'App' component and call the 'enum' function inside the component to render it conditionally.

Why we use enum in react?

An enum is a great way to have multiple conditional renderings. Let's consider the notification component again, this time we can use the enum as inlined object. The state property key helps us to retrieve the value from the object. It is much more readable compared to the switch case operator.

What number do enums start with?

Enum Values The first member of an enum will be 0, and the value of each successive enum member is increased by 1.

Is enum good for Android?

It also generates the problem of runtime overhead and your app will required more space. So overuse of ENUM in Android would increase DEX size and increase runtime memory allocation size. If your application is using more ENUM then better to use Integer or String constants instead of ENUM.


1 Answers

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.

like image 65
ChrisR Avatar answered Sep 30 '22 14:09

ChrisR