95

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;
2
  • A global constants? Are you bundling? Commented Aug 19, 2016 at 10:20
  • I use browsersync for server Commented Aug 19, 2016 at 10:21

5 Answers 5

166

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.

Sign up to request clarification or add additional context in comments.

11 Comments

export const is invalid
What do you mean? I assume you use older versions of js, in that case try exports.ACTION_INVALID instead of export const and use require('path/to/fileWithConstants').ACTION_INVALID instead of import.
events.js:160 throw er; // Unhandled 'error' event ^ SyntaxError: D:/constants.jsx: Unexpected token (2:11) class Constants extends React.Component{ 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'; }
@justColbs Its about the difference between export default and export. If you want to use export default do it like this: export default {CONSTANT_NUMBER_1: 'hello I am a constant', CONSTANT_NUMBER_2: 'hello I am also a constant'} Here I created an object with 2 different fields which represent the constants. To use it you would do: import whateverNameYouWant from 'path/to/fileWithConstants'
@justColbs: If you don't want to type myConstClass all the time (which, by convention, I'm pretty sure should be with a capital 'M' anyhow), see this answer: stackoverflow.com/a/46815846/1450294
|
42

Expanding on Monad's answer, for situations where you don't want to type myConstClass all the time:

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 { ACTION_INVALID } from 'path/to/fileWithConstants';

const errorMsg = ACTION_INVALID;

(Also, if Monad's way works better for you, I believe the convention is for 'MyConstClass' to start with a capital letter, since it's acting like a class in code.)

Comments

40

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.

3 Comments

but this way, you still CAN change the values. you just can't change the object myConstClass is pointing to.
@Bat You can just use Object.freeze(...) to make it a shallow immutable object. Nested maps, if any, will also need to be frozen similarly.
@Debajit Not sure if it was around back in 2018. Thank you! I actually haven't touched React.js in years and have switched fields a while ago lol.
15

One way to do that (not so different from other answers though) is to create a bare constants.js file and add your constants there.

module.exports = Object.freeze({
  ACTION_INVALID: 'This action is invalid',
  ACTION_VALID: 'Some other action',
});

Then you can import it

import ConstantsList from './constants';

and use

console.log(ConstantsList.ACTION_INVALID)

As the name suggests, Object.freeze() freezes objects and stops anyone from changing the values. Please note: if the values are objects themselves they are changeable (unless they are also frozen)

Comments

2

In nodejs enviroment, when using absolute path, there already is deprecated "constants" and it may conflict with yours, so it's better to create either a folder and put your constants there or create a file with name consts.

Your constants should look like that, use Object.freeze so that constants are never changed by a side effect. You should use Object.freeze for every object.

export const ACTION_INVALID = "This action is invalid!"
export const FILE_TYPES = Object.freeze({
  IMAGE: Object.freeze(["JPEG", "PNG"]),
  VIDEO: Object.freeze(["MP4", "M4V", "MOV", "3GP", "3G2", "WMV", "ASF", "AVI", "FLV", "MKV", "WEBM"])
})

Record & Tuple proposal

Thanks to the proposal, it might be possible to do this instead in future.

export const ACTION_INVALID = "This action is invalid!"
export const FILE_TYPES = #{
  IMAGE: #["JPEG", "PNG"],
  VIDEO: #["MP4", "M4V", "MOV", "3GP", "3G2", "WMV", "ASF", "AVI", "FLV", "MKV", "WEBM"]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.