React: Show Image Preview before Uploading

Updated: March 3, 2023 By: A Goodman 3 comments

This article walks you through a complete example of displaying an image preview before uploading. We are going to use React hooks and pure Javascript. No third-party packages are necessary.

The Example

Preview

The React app we are going to build has a file input. When you select an image with this file input, an image preview will show up below it. There is also a “Remove This Image” button that lets you remove the selected image and the preview as well.

Here’s the demo:

The Full Code

Create a new React app and replace the default code in ./src/App.js with the following:

// App.js
// Kindacode.com
import { useState } from "react";

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

  // This function will be triggered when the file field change
  const imageChange = (e) => {
    if (e.target.files && e.target.files.length > 0) {
      setSelectedImage(e.target.files[0]);
    }
  };

  // This function will be triggered when the "Remove This Image" button is clicked
  const removeSelectedImage = () => {
    setSelectedImage();
  };

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

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

export default App;

// Just some styles
const styles = {
  container: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    alignItems: "center",
    paddingTop: 50,
  },
  preview: {
    marginTop: 50,
    display: "flex",
    flexDirection: "column",
  },
  image: { maxWidth: "100%", maxHeight: 320 },
  delete: {
    cursor: "pointer",
    padding: 15,
    background: "red",
    color: "white",
    border: "none",
  },
};

Now run the project and test it with your own photos.

Conclusion

We’ve gone through an end-to-end example of displaying an image preview before uploading it in React. If you’d like to learn more new and exciting stuff about modern React and React Native, have a look at the following article:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Subscribe
Notify of
guest
3 Comments
Inline Feedbacks
View all comments
Hudson
Hudson
1 year ago

Very much thanks

Carlos Alexandre
Carlos Alexandre
2 years ago

Como eu faria a mesma coisa, selecionando varias imagens ?

lolipop
lolipop
8 months ago

you can use useState for saving uploaded images and then render them through map() as always

Related Articles