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;
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.
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With