By Kevin Hou
2 minute read
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 inconvenient 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:
1var text = "Hello world!"; //In file.js 2
Below this line, I must export this variable so that it can be imported in the React code:
1module.exports = {data: text} //In file.js
2
I store my string as an object called "data." I then import the contents of "file.js" in my main "App.jsx" file:
1import file from './file.js'; //In App.jsx 2
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:
1var str = file.data; //"data" is the object within "file" 2
Convert this into a usable Javascript object:
1var finalData = JSON.parse(str); 2
Your string, "Hello world!", is now stored within the variable finalData.
Hope this helps!