React: Show Image Preview before Uploading

Last updated on July 28, 2021 A Goodman Loading... One comment

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

The Example


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
import { useState } from "react";

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

  // This function will be triggered when the file field change
  const imageChange = (e) => {
    if ( && > 0) {

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

  return (
      <div style={styles.container}>

        {selectedImage && (
          <div style={styles.preview}>
            <button onClick={removeSelectedImage} style={styles.delete}>
              Remove This Image

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.


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

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Notify of
1 Comment
Inline Feedbacks
View all comments
Carlos Alexandre
Carlos Alexandre
7 months ago

Como eu faria a mesma coisa, selecionando varias imagens ?

Related Articles