Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React create constants file

How to create constants file like: key - value in ReactJs,

ACTION_INVALID = "This action is invalid!" 

and to use that in other components

errorMsg = myConstClass.ACTION_INVALID; 
like image 604
IntoTheDeep Avatar asked Aug 19 '16 10:08

IntoTheDeep


People also ask

How do you make a constants file in React?

All you have to do is take each section of your constants that are currently within index. js and put them within own their brand new file in /src/constants and link them to our constants/index. js file for easy referencing.

Where do you keep constants in React?

Organizing Constants in a React Application Since we'll only be using them in our action creators — and because these specific constants will define action types — we will store them in our actions directory in a file called ActionTypes. js .

How do you export multiple constants in React?

Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.


2 Answers

I'm not entirely sure I got your question but if I did it should be quite simple:

From my understanding you just want to create a file with constants and use it in another file.

fileWithConstants.js:

export const ACTION_INVALID = "This action is invalid!" export const CONSTANT_NUMBER_1 = 'hello I am a constant'; export const CONSTANT_NUMBER_2 = 'hello I am also a constant'; 

fileThatUsesConstants.js:

import * as myConstClass from 'path/to/fileWithConstants';  const errorMsg = myConstClass.ACTION_INVALID; 

If you are using react you should have either webpack or packager (for react-native) so you should have babel which can translate your use of export and import to older js.

like image 73
Monads are like... Avatar answered Sep 19 '22 17:09

Monads are like...


You can simply create an object for your constants:

const myConstClass = {     ACTION_INVALID: "This action is invalid!" } 

And then use it.

If you are bundling, you can export this object and then import for each component file.

like image 37
Davin Tryon Avatar answered Sep 19 '22 17:09

Davin Tryon