Basic Guidelines to Upload an Image in React JS

Image uploads are a fundamental part of modern web development. Whether you’re building a social media platform, an e-commerce site, or a simple blog, the ability for users to upload images is a common requirement.

Image uploads allows users to add images from their local devices to a website or an application. This functionality is crucial in various scenarios including user profile pictures, product images or sharing media content.

Uploading images in a React.js application involves handling user interactions to select and upload images, managing the selected images, and possibly sending them to a server.

React js provides state management and event handling features that can be used effectively for uploading images easily.

Here we can consider a scenario where an image upload icon is given and when it is clicked, images from local machine can be selected by OnClick() function. Also the selected images are sent to server i.e.,uploading to database happens indirectly by trigerring another OnChange() function.

While selected images are simultaneously uploaded to server, there may arise a need to change or remove the selected images. For this scenario, a close icon can be added over the image and when the icon is clicked, remove function can be triggered and so the selected image can be removed from UI and also from the server.

The code to achieve this functionality can be as simple as follows:

To select images:

<img src={image} alt=”default” onClick={handleImageClick}/>

<input type =”file” id =”fileInput” style ={{display : “none” }} onChange ={handleFileChange}/>

Here image is the icon placed and when it is clicked it allows user to select images from their local machine. Any number of images can be selected with this handleImageClick().

const handleImageClick =() => {

document.getElementById(‘fileInput’).click();

};

Storing the selected Image:

Once the image is selected, it needs to be converted to proper format that the server accepts. For this step, look at the below code.

const handlefilechange = (event) => {

const file = event.target.files[0];

const imageUrl = URL.createOjectURL(file);

setselectedImages(prevImages => […prevImages, imageUrl]);

List(prevList => […prevList, file]);

uploadImage(file);

}

handlefilechange function is called when the user selects an image. It receives the event object, which contains information about the selected file. Here’s what this function does:

  • It extracts the selected file using event.target.files[0]
  • It creates a URL for the selected file using URL.createObjectURL(file)
  • It updates the state using useState hooks to store the selected images and the list of files.
  • It calls uploadimage(file) to upload the image to the server.

Uploading the image to server:

Here the selected and stored images are sent to the server using API call. The response data can be again set to state variable for accessing throughout the application.

uploadImage = (file ) = > {

const formData = new formData();

formData.append(‘file’,file);

//upload file to server through any API call methods

Const fileUrl = apiresponse.file_url;

//Update the list with the file URL

}

Removing the selected/uploaded image:

This function allows users to remove a selected image from the list. It filters the selectedImages array to exclude the image at the specified index. This can be achieved by placing a Clear icon over the images.

<button

onClick = {() => handleRemoveImaege(index)}

style ={{

position : “absolute”,

top : “0px”,

right : “-1px”,

border : “none”,

cursor : “pointer”,

color : “white”,

}}

<ClearIcon />

</button>

ClearIcon can be imported from materailui/icons.

const handleRemoveImage = ( index) => {

setSelectedImages(prevImages => prevImages.filter((_,i)=> I !== index));

};

Rendereing the images:

To render the images , we need to map over the selectedimages array and display the images as <img>  as follows:

{selectedImages.map((image,index) => (

<div key = {index}>

<img

src = {image}

alt = {`Selected $ {index}`}

/>

Leave a Reply