Skip to content
Advertisement

Include JSON files into React build

I know this question maybe exist in stack overflow but I didn’t get any good answers, and I hope in 2020 there is better solution.

In my react app I have a config JSON file, it contains information like the title, languages to the website etc.. and this file is located in ‘src’ directory

 {
  "headers":{
    "title":"chat ",
    "keys":"chat,asd  ,
    "description":" website"
  },
  "languages":{
    "ru":"russian",
    "ar":"arabic",
    "en":"English"
  },
  "defaultLanguage":"ru",
  "colors":{
    "mainColor":"red",
    "primary":"green",
    "chatBackGround":"white"
  }
}

I want to make my website easy to edit after publishing it, but after I build my app, I can’t find that settings.json file there in build directory.

I find out that files in public directory actually get included to build folder, I tried to put my settings.JSON in public, but react won’t let me import anything outside of src directory

I found other solutions like this one but didn’t work https://github.com/facebook/create-react-app/issues/5378

Also I tried to create in index.html a global var like (window.JSON_DATA={}), and attach a JS object to it and import it to App.js, but still didn’t work.

How can I make a settings JSON file, and have the ability to edit it after publishing the app?

Advertisement

Answer

Add your settings.json to the public folder. React will copy the file to the root of build. Then load it with fetch where you need it to be used. For example if you need to load setting.json to the App.js then do the next:

function App() {

    const [state, setState] = useState({settings: null});

    useEffect(()=>{
        fetch('settings.json').then(response => {
            response.json().then(settings => {
                // instead of setting state you can use it any other way
                setState({settings: settings});
            })
        })
    })
}

If you use class-components then do the same in componentDidMount:

class CustomComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {settings: null};
    }

    componentDidMount() {
        fetch('settings.json').then(response => {
            response.json().then(settings => {
                this.setState({settings: settings});
            })
        })            
    }
}

Then you can use it in render (or any other places of your component):

function App() {

    ...

    return (
        {this.state.settings && this.state.settings.value}
    ) 
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement