Categories
JavaScript Answers

How to get image preview before uploading in React?

Spread the love

Sometimes, we want to get image preview before uploading in React.

In this article, we’ll look at how to get image preview before uploading in React.

How to get image preview before uploading in React?

To get image preview before uploading in React, we read the selected file into a base64 URL string.

For instance, we write

const App = () => {
  const [selectedImage, setSelectedImage] = useState();

  const imageChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      setSelectedImage(e.target.files[0]);
    }
  };

  const removeSelectedImage = () => {
    setSelectedImage();
  };

  return (
    <>
      <div>
        <input accept="image/*" type="file" onChange={imageChange} />

        {selectedImage && (
          <div>
            <img src={URL.createObjectURL(selectedImage)} alt="Thumb" />
            <button onClick={removeSelectedImage}>Remove This Image</button>
          </div>
        )}
      </div>
    </>
  );
};

to add a file input and an img element.

We set the file input’s onChange prop to the imageChange function.

In it, we get the selected file e.target.files[0] and set that as the value of the selectedImage state.

And then we convert that to a base64 URL with URL.createObjectURL.

Conclusion

To get image preview before uploading in React, we read the selected file into a base64 URL string.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *