Menethil
Menethil

Reputation: 27

How to use require() in React

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

Upvotes: 0

Views: 333

Answers (1)

Feenix Net
Feenix Net

Reputation: 228

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;

Upvotes: 2

Related Questions