skip to Main Content

I’m new to React.
I was wondering how to read and write to JSON file and most people use require(fs) etc…
I know that require is not standard browser function (or Reacts) but I’m confused how to connect React with it?
I already have node modules in that folder and I thought that require function would be included in that (as when I worked with node.js)?

I thought that require would already be included since I have node_modules that came with react in that folder

2

Answers


  1. require(‘fs’) is commonly used in node.js to work with the file system.
    However, in React which runs in the browser, you cannot use require(‘fs’) because ‘fs’ is a node.js module, and the browser environment doesn’t have access to the file system directly for security reasons.
    React is a front-end library that runs in the browser, whereas ‘fs’ is part of Node.js, which is a server-side runtime. Browsers cannot interact with the file system directly like node.js can, so trying to use ‘fs’ in a React application will result in erros.

    If you want to read data from a static json file in react, you can do so using ‘import’ or ‘fetch.

    -using ‘import’
    you can place the josn file in your ‘public’ directory or ‘src directory and import it directly.

    import data from './data.json'
    function App( {
    console.log(data);
    return(
    <div>
    <h1> Data from json file</h1>
    <pre>{JSON.stringfy(data, null, 2)}</pre>
    </div>
    );
    }
    
    export default App;
    
    • Using ‘fetch’
      you can also fetch the Json file if it’s located in your ‘public’ directory.

      function App() {
      cosnt [data, setData] = React.useState(null);

      React.useEffect(()=> {
        fetch('/data.json')
          .then((response) => response.json())
          .then((jsonData) => setData(jsonData));
      }, []};
      
      return(
        <div>
          <h1> Data from json file</h1>
          <pre>{JSON.stringfy(data, null, 2)}</pre>
        </div>
        );
      

      }

      export default App;

    Login or Signup to reply.
  2. It’s great that you’re diving into React! You’re correct that require('fs') (used to interact with the file system) is a Node.js function and not available in the browser environment where React typically runs.

    How React and Node.js Differ:

    • React is a front-end library that runs in the browser, which doesn’t have direct access to the file system for security reasons.
    • Node.js, on the other hand, is a back-end runtime that can access the file system using modules like fs.

    How to Handle JSON in React:

    1. Reading JSON:

      • If you have a static JSON file, you can import it directly in React:
        import data from './data.json';
        console.log(data);
        
      • If you need to fetch JSON data dynamically, use the fetch API or axios:
        fetch('/path-to-json.json')
          .then(response => response.json())
          .then(data => console.log(data));
        
    2. Writing JSON:

      • Since the browser can’t write to files directly, you typically handle this on the server side using Node.js. You can create a Node.js API that your React app can communicate with using fetch or axios.
      • For example, your React app can send data to a Node.js server, which will then write to a JSON file:
        fetch('/api/save-data', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data),
        });
        
      • On the Node.js server, you’d handle the file writing using fs:
        const fs = require('fs');
        app.post('/api/save-data', (req, res) => {
          const data = req.body;
          fs.writeFileSync('data.json', JSON.stringify(data));
          res.sendStatus(200);
        });
        

    Summary:

    • React: Use fetch or axios to read JSON data or send data to a server.
    • Node.js: Use the fs module to handle reading/writing files on the server.

    This approach keeps the front-end and back-end roles clear while allowing your React app to interact with JSON data efficiently.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search