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.
Code:
export const MESSAGE = 'Welcome to LearnShareIT'; export const ERROR = 'Opps 404 not found';
import { MESSAGE, ERROR } from './Variables'; console.log(MESSAGE); console.log(ERROR);
Output:
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.
Code:
export const NAME = "John"; export default NAME;
import name from './Variables'; console.log(name);
Output:
John
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
Summary
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.

Hi, my name’s Nathaniel Kirk. I’m interested in learning and sharing knowledge about programming languages. My strengths are C, C++, Python, HTML, CSS, Javascript, and Reactjs. If you have difficulty with them, don’t worry. I’m here to support you.
Name of the university: PTIT
Major: IT
Programming Languages: C, C++, Python, HTML, CSS, Javascript, Reactjs