< Return to all blogs
Using Javascript Variables From Another File in ReactJS
How to import variables from another Javascript file
The project I’ve been working on requires data entry that isn’t always easy to organize if they are kept locally in my React code. I’ve been declaring my data as a getInitialState() which is both inconvienient and messy. To work around this, I’m keeping my data in a seperate Javascript file called “file.js.”
I keep my data in a JSON format, but as a string:
var text = "Hello world!"; //In file.js
Below this line, I must export this variable so that it can be imported in the React code:
module.exports = {data: text} //In file.js
I store my string as an object called “data.” I then import the contents of “file.js” in my main “App.jsx” file:
import file from './file.js'; //In App.jsx
The contents of the object I exported in the other file is being stored as the variable “file” here. I can then convert the contents of “file” to an object:
var str = file.data; //"data" is the object within "file"
Convert this into a usable Javascript object:
var finalData = JSON.parse(str);
Your string, “Hello world!”, is now stored within the variable finalData.
Hope this helps!
Posted in Web Development with Javascript, ReactJS, ES6