Create Single & Multiple Image File Preview in React App

This tutorial guides on building single and multiple image upload and display image file preview in React app with the help of URL.createObjectURL() method.

The URL.createObjectURL() static method creates a DOMString comprising a URL interpreting the object yielded in the parameter. The URL lifetime is bound to the document in the window on which this was formulated. It gives the new object URL that manifests the designated File object or Blob object.

const fileObjectURL = URL.createObjectURL(object)

object: A File, Blob, or MediaSource object, It constructs an object URL.

return value: A DOMString contains an object URL that is used to refer to the contents of the specified source object.

Throughout this tutorial, we will create simple react app, in the same audacity we build the image preview functionality for single and multiple image file upload.

React Single and Multiple Image Preview Example

  • Step 1: Create React Project
  • Step 2: Add Bootstrap Pacakge
  • Step 3: Create Single Image File Preview Component
  • Step 4: React Multiple Image Files Preview
  • Step 5: Update App.js File
  • Step 6: Start React App

Create React Project

Let us begin installing the new react app using the create-react-app; it offers the quintessential environment with the utmost fidelity, which is better for learning react development.

npx create-react-app react-demo-app

Move to project folder:

cd react-demo-app

Add Bootstrap Pacakage

In the next segment of this guide, we will install the Bootstrap package into the react app; it helps in styling the immaculate UI component in exorbitantly less time.

npm install bootstrap

In order to add and use the Bootstrap UI components in React, you must import the Bootstrap CSS in the main src/App.js file.

import React from 'react';
import './App.css';

import '../node_modules/bootstrap/dist/css/bootstrap.min.css';


function App() {
  return (
    <div className="App">

    </div>
  );
}

export default App;

Create Single Image File Preview Component

Get inside the src folder, create a new directory likewise name it components; after that, create single-file-upload.component.js for handling the single-image preview.

Open src/components/single-file-upload.component.js, update the following code in the file.

import React, { Component } from 'react';

export default class SingleFileUploadComponent extends Component {

    constructor(props) {
        
        super(props)

        this.state = {
            file: null
        }
        this.fileUpload = this.fileUpload.bind(this)
        this.uploadImage = this.uploadImage.bind(this)
        
    }

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

    uploadImage(event) {
        event.preventDefault()
        console.log(this.state.file)
    }

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

                <div className="form-group mb-3">
                    <input type="file" onChange={this.fileUpload} className="form-control" />
                </div>
                <button type="button" onClick={this.uploadImage} className="btn btn-danger">Upload Single File</button>
            </form >
        )
    }
}

React Multiple Image Files Preview

In the same way head over to src/components directory, over and above that create multi-file-upload.component.js file.

Open src/components/multi-file-upload.component.js, add the suggested code in the file.

import React, { Component } from 'react';

export default class MultiFileUploadComponent extends Component {

    filesArray = [];
    FilesCollection = [];

    constructor(props) {

        super(props)

        this.state = {
            file: [null]
        }
        this.multiImagePreview = this.multiImagePreview.bind(this)
        this.imagePreview = this.imagePreview.bind(this)

    }

    multiImagePreview(event) {
        this.filesArray.push(event.target.files)
        for (let i = 0; i < this.filesArray[0].length; i++) {
            this.FilesCollection.push(URL.createObjectURL(this.filesArray[0][i]))
        }
        this.setState({ file: this.FilesCollection })
    }

    imagePreview(event) {
        event.preventDefault()
        console.log(this.state.file)
    }

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

                <div className="form-group mb-3">
                    <input type="file" className="form-control" onChange={this.multiImagePreview} multiple />
                </div>
                <button type="button" className="btn btn-success" onClick={this.imagePreview}>Upload Multi Images</button>
            </form >
        )
    }
}

Update App.js File

In this step, you require to conjugate or add the single image preview similarly multiple image preview components into the main src/App.js file.

import React, { Component } from 'react';
import './App.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import SingleFileUploadComponent from './components/single-file-upload.component';
import MultiFileUploadComponent from './components/multi-file-upload.component';

class App extends Component {
  render() {
    return (
      <div className="container">
        <div className="row">
          <div className="col-md-6">
            <div className="card">
              <div className="card-header">
                Single Image Preview
              </div>
              <div className="card-body">
                <SingleFileUploadComponent />
              </div>
            </div>
          </div>
          <div className="col-md-6">
            <div className="card">
              <div className="card-header">
                Multiple Image Preview
              </div>
              <div className="card-body">
                <MultiFileUploadComponent />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default App;

Start React App

Theoretically, at the end of this extensive guide, we need to start the react app; we may run the app by running the recommended command through the terminal window.

npm start

Open browser, type the url, and test the react select app.

http://localhost:3000

React multiple image preview

Conclusion

Image preview functionality is useful for showing users what image file they are likely to upload on the server; through this tutorial, we have shared how to build a Single and Multiple Image Preview feature in React application.