React 17 Tutorial- Single And multiple Images Upload Preview

React Single and Multiple Image Upload Preview Tutorial; In this React tutorial, we will get to learn how to show an image preview before uploading it to the server in a React app.

We will be creating a basic react app in which we will use an HTML file input field along with some events to show an image preview.

What is URL.createObjectURL() status method?

We will use this method to get the image preview URL since 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 that represents the contents of the particular source object.

 

React 17 Single And Multiple Images Upload Preview

See the below steps:

 

Step 1- Install React With Bootstrap

First of all, we will install React app with Bootstrap 4. Then, we execute the below command:

npx create-react-app react-image-preview

Further, we will navigate to React image preview app directory:

cd react-image-preview

Then, we will install the Bootstrap 4 framework:

npm install bootstrap --save

 

Afterward, we need to import the bootstrap.min.css in the src/App.js file from the 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;

Thereafter, we run the React app in the browser:

npm start

 

Step 2- Create Single Image Upload Preview

Here, we will create the src>components directory and then create two component files inside it. We name these files single-image-upload.component.js and multiple-image-upload.component.js.

Further, we have to add the given code in the 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 have defined the HTML form and added the REact events with HTML attributes. We initiated the input file field state in the constructor method. Then, we set the state of the input field in the uploadSingleFile() method.

Next, we defined the if statement inside the render() method because initially, the 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() API in the image upload preview. We have used the URL.createObjectURL() static method which produces a DOMString including a URL representing the object provided in the parameter.

 

Step 3- Multiple Images Upload Preview In React

Now, we will be building multiple images upload preview component for which we include the given 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 >
        )
    }
}

We define fileObj array variable. We will insert the image preview URLs in this array using the URL.createObjectURL() method for showing multiple images preview before uploading to the server.

Then, we defined the fileArray array. In this, we will push the images to the preview URL. We are using JavaScript’s map() method to iterate over the fileArray. Then, we are setting up the tag and pass the image URL returned by the map method.

 

Conclusion

We have reached the end of this React Single And Multiple Images Upload Preview Tutorial With Example. Hope that the steps were quite easy to follow and implement.

 

Thanks

Leave a Reply

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