React is a popular front-end library that is used to build user interfaces. One common feature of many web applications is the ability to upload and display images. In this article, we will demonstrate how to upload an image in a React application and display it on the page. We will also provide the source code so that you can easily implement this feature in your own React projects.
To start, we will create a simple React component that includes a file input field and an image tag. When the user selects an image file, we will use the FileReader API to read the file contents and display the image on the page.
Here is the code for our React component:
//SCRIPT SOURCE CODE STARTING
import React, { useState, useRef } from "react";
import "./style.css";
function ImageUpload() {
const [image, setImage] = useState(null);
const hiddenFileInput = useRef(null);
const handleImageChange = (event) => {
const file = event.target.files[0];
const imgname = event.target.files[0].name;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onloadend = () => {
const img = new Image();
img.src = reader.result;
img.onload = () => {
const canvas = document.createElement("canvas");
const maxSize = Math.max(img.width, img.height);
canvas.width = maxSize;
canvas.height = maxSize;
const ctx = canvas.getContext("2d");
ctx.drawImage(
img,
(maxSize - img.width) / 2,
(maxSize - img.height) / 2
);
canvas.toBlob(
(blob) => {
const file = new File([blob], imgname, {
type: "image/png",
lastModified: Date.now(),
});
console.log(file);
setImage(file);
},
"image/jpeg",
0.8
);
};
};
};
const handleUploadButtonClick = (file) => {
var myHeaders = new Headers();
const token = "adhgsdaksdhk938742937423";
myHeaders.append("Authorization", `Bearer ${token}`);
var formdata = new FormData();
formdata.append("file", file);
var requestOptions = {
method: "POST",
headers: myHeaders,
body: formdata,
redirect: "follow",
};
fetch("https://trickuweb.com/upload/profile_pic", requestOptions)
.then((response) => response.text())
.then((result) => {
console.log(JSON.parse(result));
const profileurl = JSON.parse(result);
setImage(profileurl.img_url);
})
.catch((error) => console.log("error", error));
};
const handleClick = (event) => {
hiddenFileInput.current.click();
};
return (
<div className="image-upload-container">
<div className="box-decoration">
<label htmlFor="image-upload-input" className="image-upload-label">
{image ? image.name : "Choose an image"}
</label>
<div onClick={handleClick} style={{ cursor: "pointer" }}>
{image ? (
<img src={URL.createObjectURL(image)} alt="upload image" className="img-display-after" />
) : (
<img src="./photo.png" alt="upload image" className="img-display-before" />
)}
<input
id="image-upload-input"
type="file"
onChange={handleImageChange}
ref={hiddenFileInput}
style={{ display: "none" }}
/>
</div>
<button
className="image-upload-button"
onClick={handleUploadButtonClick}
>
Upload
</button>
</div>
</div>
);
}
export default ImageUpload;
//SCRIPT SOURCE CODE ENDING
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
//STYLE SOURCE CODE ENDING
.image-upload-container {
padding: 2rem;
display: flex;
justify-content: center;
align-items: center;
height: 90vh;
}
.box-decoration {
border: 2px dashed #ccc;
border-radius: 5px;
padding: 130px 100px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.image-upload-label {
font-size: 1.5rem;
font-weight: bold;
margin-bottom: 1rem;
cursor: pointer;
}
.image-upload-input {
display: none;
}
.image-upload-button {
background-color: #4CAF50;
border: none;
color: white;
padding: 0.8rem 1.2rem;
margin-top: 1rem;
cursor: pointer;
border-radius: 5px;
}
.image-upload-button:hover {
background-color: #3e8e41;
}
.img-display-before {
height: 200px;
width: 200px;
margin-left: 35px;
}
.img-display-after {
height: 200px;
width: 200px;
border-radius: 100%;
}
//STYLE SOURCE CODE ENDING
Let's go through this code step-by-step. First, we import the useState and useRef hook from React. This allows us to create a state variable that we can update later on. We also define a function called ImageUpload, which will be our main component.
Inside the function, we use the useState hook to create a state variable called image, which will store the URL of the uploaded image. We also define a function called handleImageChange, which will be called when the user selects an image file.
Inside handleImageChange, we get the file object from the input event and create a new instance of the FileReader API. We then set the onload event handler to a function that will update the image state variable with the base64-encoded contents of the uploaded file. Finally, we call the readAsDataURL method of the reader object to read the contents of the file.
In the return statement of our component, we create an input field of type "file" and add an event listener that will call handleImageChange when the user selects a file. We also add an img tag that will display the uploaded image, if there is one. We use a ternary operator to conditionally render the img tag based on whether image is truthy or falsy.
That's it! With this code, you should be able to upload an image in your React application and display it on the page.
To summarize, we have demonstrated how to upload an image in a React application and display it on the page using the FileReader API. We have also provided the source code for our React component so that you can easily implement this feature in your own projects. Happy coding!