# How to Use JSONEditor in a React App

[JSONEditor](https://www.npmjs.com/package/@json-editor/json-editor) is a <mark>powerful tool for editing JSON data in a visual interface</mark>. In this tutorial, we'll walk through how to integrate JSONEditor into a React app to import JSON data from a file, edit it using the JSONEditor interface, and save the updated JSON data back to a file.

## **Getting Started**

First, install the [JSONEditor](https://jsoneditoronline.org/) library using npm:

```bash
npm install jsoneditor
```

Next, create a new React component to house the [JSONEditor](https://www.bytescrum.com/) and its functionality. Here's a basic example:

```javascript
import React, { useState, useEffect, useRef } from 'react';
import JSONEditor from 'jsoneditor';

const App = () => {
    const [jsonData, setJsonData] = useState(null);
    const editorRef = useRef(null);

    useEffect(() => {
        if (!editorRef.current) {
            return;
        }

        const fetchData = async () => {
            try {
                // Import the JSON file
                const response = await import('./data.json');
                const initialJsonData = response.default;

                // Create the editor
                const options = {};
                const editor = new JSONEditor(editorRef.current, options);
                editorRef.current.jsonEditor = editor; // Store the editor instance

                // Set the JSON data
                editor.set(initialJsonData);

                setJsonData(initialJsonData);

                // Listen for changes to the JSON data in the editor
                editorRef.current.jsonEditor.options.onChange = () => {
                    const updatedJsonData = editorRef.current.jsonEditor.get();
                    setJsonData(updatedJsonData);
                };

                // Cleanup
                return () => {
                    editor.destroy();
                };
            } catch (error) {
                console.error('Error loading JSON file:', error);
            }
        };

        fetchData();
    }, []);

    const handleSave = async () => {
        if (!jsonData) {
            console.error('No JSON data to save');
            return;
        }

        try {
            await fetch('http://localhost:3000/file/write', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(jsonData)
            });
            console.log('JSON data saved successfully');
        } catch (error) {
            console.error('Error saving JSON data:', error);
        }
    };

    return (
        <div>
            {/* when using the mode "code", it's important to specify charset utf-8 */}
            <meta charSet="utf-8" />

            <link href="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/10.0.2/jsoneditor.min.css" rel="stylesheet" type="text/css" />
            <div ref={editorRef} style={{ width: '100%', height: '100vh' }}></div>

            <button onClick={handleSave}>Save</button>

            <script src="https://cdnjs.cloudflare.com/ajax/libs/jsoneditor/10.0.2/jsoneditor.min.js"></script>
        </div>
    );
};

export default App;
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1711688175881/d086c505-7ac5-4bb7-a3af-8efd5806a446.png align="center")

# **Writing JSON Data to a File using Express**

We'll explore how to create a simple Express.js server that accepts JSON data in a POST request and writes it to a file using the Node.js `fs` module.

## **Setting Up the Express Server**

First, let's set up a basic Express server with a route that handles POST requests to write JSON data to a file. Start by creating a new Express project and installing the necessary dependencies:

```bash
npm init -y
npm install express fs
```

Next, create a new file called `app.js` and add the following code:

```javascript
// app.js

const express = require('express');
const fs = require('fs');
const app = express();
const port = 3000;

app.use(express.json());

app.post('/file/write', (req, res) => {
    const data = req.body;
    try {
        fs.writeFileSync(
            '/path/to/your/file.json', // Specify the path to your JSON file
            JSON.stringify(data, null, 2),
        );
        res.send({ message: 'File written successfully' });
    } catch (error) {
        res.status(500).send({ message: 'Error writing file', error });
    }
});

app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
});
```

Replace `/path/to/your/file.json` with the actual path to your JSON file. This route handler accepts JSON data in a POST request and uses `fs.writeFileSync` to write the data to the specified file. If an error occurs during the write operation, it sends a 500 status code along with an error message.

## **Testing the Endpoint**

To test the endpoint, you can use a tool like Postman or curl to send a POST request to [`http://localhost:3000/file/write`](http://localhost:3000/file/write) with JSON data in the request body. For example:

```bash
curl -X POST http://localhost:3000/file/write -H "Content-Type: application/json" -d "{\"name\": \"John\", \"age\": 30}"
```

This will write the JSON data `{"name": "John", "age": 30}` to the specified file.

<details data-node-type="hn-details-summary"><summary>Summary</summary><div data-type="detailsContent">In this example, we're using the <a target="_blank" rel="noopener noreferrer nofollow" href="https://www.tutorialspoint.com/online_json_editor.htm" style="pointer-events: none">JSONEditor</a> library to create a JSON editor in a React component. The component loads JSON data from a file (<code>data.json</code>), displays it in the editor, allows the user to edit the JSON data, and provides a "Save" button to save the updated JSON data back to the file.</div></details>
