React 16+ Single and Multiple Images Upload Preview

By Digamber Rawat Last updated on
Today in this React image upload preview tutorial, we are going to learn how to show image preview before uploading to the server in a React app. We will create a basic react app in which we will use an HTML file input field along with some events to show an image preview.

Let’s understand the URL.createObjectURL() static method, we are going to use this method to get the image preview URL. This method generates a DOMString including a URL describing the object yielded in the parameter. The URL life is tied to the document in the window on which it was created. The new object URL outlines the designated File object or Blob object.

myObjectURL = URL.createObjectURL(object);

object: It’s a Blob, File or MediaSource object, It creates an object URL.

Return value: A DOMString including an object URL which represents the contents of the particular source object.

React 16+ Single and Multiple Images Upload Preview

Let’s install React app for image upload preview demo.

Install React with Bootstrap

In the very first step, Install React app with Bootstrap 4. Execute the given below command.

npx create-react-app react-image-preview

Navigate to React image preview app directory.

cd react-image-preview

Next, install Bootstrap 4 framework.

npm install bootstrap --save

Next, Import bootstrap.min.css in src/App.js file from node_modules folder:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import './App.css';

function App() {
  return (
    <div className="App">
      <h3>Image Upload Preview in React</h3>
    </div>
  );
}

export default App;

Next, run the React app in the web browser.

npm start

Create Single Image Upload Preview

Create src > components directory and create two component files inside of it. Name these files single-image-upload.component.js and multiple-image-upload.component.js.

Add below code in single-image-upload.component.js file.

import React, { Component } from 'react';

export default class SingleImageUploadComponent extends Component {

    constructor(props) {
        super(props)
        this.state = {
            file: null
        }
        this.uploadSingleFile = this.uploadSingleFile.bind(this)
        this.upload = this.upload.bind(this)
    }

    uploadSingleFile(e) {
        this.setState({
            file: URL.createObjectURL(e.target.files[0])
        })
    }

    upload(e) {
        e.preventDefault()
        console.log(this.state.file)
    }

    render() {
        let imgPreview;
        if (this.state.file) {
            imgPreview = <img src={this.state.file} alt='' />;
        }
        return (
            <form>
                <div className="form-group preview">
                    {imgPreview}
                </div>

                <div className="form-group">
                    <input type="file" className="form-control" onChange={this.uploadSingleFile} />
                </div>
                <button type="button" className="btn btn-primary btn-block" onClick={this.upload}>Upload</button>
            </form >
        )
    }
}

We defined the HTML form and added the React events with HTML attributes. Initiate the input file field state in the constructor method, then set the state of the input filed in uploadSingleFile() method.

Next, we defined the if statement inside the render() method, because initially, image tag doesn’t have any preview url. We are setting up the image preview url when the user uploads the image.

We took a simple approach rather than using FileReader() web API in image upload preview. We used the URL.createObjectURL() static method which produces a DOMString including a URL representing the object provided in the parameter.

React Image Upload Preview

Multiple Images Upload Preview in React

Now, let’s build multiple images upload preview component, include the given below code within the multiple-image-upload.component.js file.

import React, { Component } from 'react';

export default class MultipleImageUploadComponent extends Component {

    fileObj = [];
    fileArray = [];

    constructor(props) {
        super(props)
        this.state = {
            file: [null]
        }
        this.uploadMultipleFiles = this.uploadMultipleFiles.bind(this)
        this.uploadFiles = this.uploadFiles.bind(this)
    }

    uploadMultipleFiles(e) {
        this.fileObj.push(e.target.files)
        for (let i = 0; i < this.fileObj[0].length; i++) {
            this.fileArray.push(URL.createObjectURL(this.fileObj[0][i]))
        }
        this.setState({ file: this.fileArray })
    }

    uploadFiles(e) {
        e.preventDefault()
        console.log(this.state.file)
    }

    render() {
        return (
            <form>
                <div className="form-group multi-preview">
                    {(this.fileArray || []).map(url => (
                        <img src={url} alt="..." />
                    ))}
                </div>

                <div className="form-group">
                    <input type="file" className="form-control" onChange={this.uploadMultipleFiles} multiple />
                </div>
                <button type="button" className="btn btn-danger btn-block" onClick={this.uploadFiles}>Upload</button>
            </form >
        )
    }
}

Define fileObj array variable, we will insert image preview urls in this array using URL.createObjectURL() method for showing multiple images preview before uploading to the server.

Next, we defined fileArray array in this array we will push images to preview url we are using JavaScript’s map() method to iterate over the fileArray. Then we are setting up the tag and passing the image url return by map method.

React multiple Images Upload Preview

Conclusion

We have completed React single and multiple images upload preview tutorial with example. I hope this tutorial will be helpful to you, please consider it sharing with other.

Git Repo

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.