How to import Variables from another file in React

This article will show you how to import Variables from another file in React with two methods importing by name and using export default variables along with detailed examples.

Import variables from another file in React

Import by name method

In React, the export name is used to export multiple things from a module by adding the export keyword to their report. Exported things will be distinguished by name. Then enter the ones we need to use by surrounding them with curly braces { }. The name of the imported module must be the same as the name of the exported module. 

We can use this to pass each variable one by one that you need to pass between components. Let’s see the code and file structure below to understand how it works.


export const MESSAGE = 'Welcome to LearnShareIT';
export const ERROR = 'Opps 404 not found';
import { MESSAGE, ERROR } from './Variables';


Welcome to LearnShareIT
Opps 404 not found

In the Variables file, we define and export the const values ​​that the program asks to transmit. For component import variables, we will use named import with {} syntax, the values ​​passed inside curly braces are the names of previously defined variables. Then we need to name this variable to use the imported variables.

Using export default variables

In Javascript ES6, only one default output is allowed per file. Default Export can be for a function, class, or object. Import naming is independent of export default, and we can use any name we want. So each file can only export a single default value. As in the example below, I will export a default variable from the variable file and import it into another file.


export const NAME = "John";
export default NAME;
import name from './Variables';



In the file to import, you can name anything to be imported because only one value is exported. This method is often used with a function component, but we recommend something other than this method with variables because it will waste resources. Wish you success with the methods mentioned in the article


To summarize, two ways to import variables from another file in React have been mentioned in the article. However, I recommend using named imports to easily pass multiple variables and manage them.

Leave a Reply

Your email address will not be published. Required fields are marked *