React File upload

Hey there,Today we are going to discuss about react file uploading.We MERN developers use multer from our file uploading.But in some case when we are doing a demo project or practicing some thing then if i have to setup whole multer code base then it is horrible.For that today i am going to show you how can you upload a file using a react package called react-file-base64.

Today we are going to build the following app

Now,at first setup out project

create a folder on Desktop and get init it

$ cd Desktop
$ mkdir react-file-upload
$ cd react-file-upload

and then create brand new react project with typescript

$ npx create-react-app ./ --template typescript

Now clean up all unnecessary files and get started

At the top of App.tsx file import

import FileBase from 'react-file-base64'

Now add some jsx to out components

<form onSubmit={handleSubmit}>
      <FileBase/>
      <button type="submit">Send</button>
      <div>
        <img src='' alt="react project" />
      </div>
    </form>

And add some state and change handler for controlling the form

type State = {
  image: string;
};
const [data, setData] = useState<State>({
    image: "",
  });
  const [image, setImage] = useState("");
  const handleSubmit = (e: React.SyntheticEvent) => {
    e.preventDefault();
  };

We have to give three props to our FileBase Component they are type,multiple,onDone.So,give them to FileBase

<FileBase
        type="file"
        multiple={false}
        onDone={({ base64 }: { base64: string }) =>
          setData({ ...data, image: base64 })
        }
      />

Here onDone works same as onChange.onDone receives a parameter which contains base64.You should console log that parameter to see what the parameter contains.Now set base64 to the state.

Now add console log the data form onSubmit handler

const handleSubmit = (e: React.SyntheticEvent) => {
    e.preventDefault();
    console.log(data);
  };

Now if you select a photo and submit the form you should see something in the console.You should see and object containing something like this

you see the image property contains something like string.This string goes into src attribute of an img element.

Now you can save this string to your database.So, you no longer need to store a lot of image in in folder just save this string.

In this application we are going to use this string to our img element

Change image elements src like this

<img src={image ? image : ""} alt="react project" />

and set image string to image state from submit handler

const handleSubmit = (e: React.SyntheticEvent) => {
    e.preventDefault();
    setImage(data.image);
  };

now go to your browser and try to upload images.

Thank you for being with me so long.See you.Bye!

24