Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React app - upload and read JSON file into variable without a server?

I'm building a JSON editor in React and right now I'm just fetching a json file from a static folder on the server and sticking it in a variable. I'd like to be able to use a file input and select any json file and read it into the variable.

Is this possible without a server?

That said, I also tried using an Express/Cors server but it's a bit outside my wheelhouse and I'm not sure how to install / run it on the production domain where this editor will live.

like image 335
Kirk Ross Avatar asked Feb 03 '26 01:02

Kirk Ross


1 Answers

Have an input of type file and maintain a state and update the state upon onChange

working demo is here

Code snippet

import React, { useState } from "react";

export function Upload({ children }) {
  const [files, setFiles] = useState("");

  const handleChange = e => {
    const fileReader = new FileReader();
    fileReader.readAsText(e.target.files[0], "UTF-8");
    fileReader.onload = e => {
      console.log("e.target.result", e.target.result);
      setFiles(e.target.result);
    };
  };
  return (
    <>
      <h1>Upload Json file - Example</h1>

      <input type="file" onChange={handleChange} />
      <br />
      {"uploaded file content -- " + files}
    </>
  );
}
like image 97
gdh Avatar answered Feb 04 '26 15:02

gdh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!