How to Upload Images to Cloudinary With a React App

Bassit Owolabi
Geek Culture
Published in
5 min readMar 29, 2021

Introduction

Sometimes while working on applications that requires the use of images,a simple process like uploading an image to a server could become pretty difficult. Cloudinary makes this a very easy thing to achieve. We can upload and manage images directly from the frontend. In this article,I’ll be showing you a step by step process on how to create and set up your cloudinary account for the image upload process and as well as how to upload the images from a react web application.

Prerequisites

  • Basic understanding of javascript
  • Basic knowledge of React
  • The latest version of nodejs installed on your machine
  • the latest version of React
  • A cloudinary account

1. Creating and setting up your cloudinary account

Head over to Cloudinary. Create a new account or login if you already have one. Once logged in,your homepage should look like the one in the image below. Go ahead and click on upload

Scroll down a little bit to where you have enable Unsigned uploading and click to enable. You’d notice I have mine enabled already.

Click on Add upload preset. This helps you define the default behaviour for your uploads.

Fill the upload preset name with any name of your choice then go ahead to change the signing mode to Unsigned. This lets you upload without authorization.

click on save and we’re done here for now. Take note of your Upload Preset name as it will be required later.

2. Setting up React

Run this command below to create your react app in seconds using a terminal of your choice

npx create-react-app react-image-app

Run this command to change directory into the folder you just created and start it up

cd react-image-app && npm start

Now that we have react set up, Replace your app.js file with this code

import React, { useState } from 'react'const App = () => {const [image, setImage ] = useState("");const [ url, setUrl ] = useState("");
const uploadImage = () => {const data = new FormData()data.append("file", image)data.append("upload_preset", "tutorial")data.append("cloud_name","breellz")
fetch(" https://api.cloudinary.com/v1_1/breellz/image/upload",{method:"post",body: data}).then(resp => resp.json()).then(data => {setUrl(data.url)}).catch(err => console.log(err))}return (<div><div><input type="file" onChange= {(e)=> setImage(e.target.files[0])}></input><button onClick={uploadImage}>Upload</button></div><div><h1>Uploaded image will be displayed here</h1><img src={url}/></div></div>)}export default App;

I won’t be focusing on styling, pardon me as the end product looks really ridiculous lol. so you can style as you please.

Here’s the code explanation

import React, { useState } from 'react'const App = () => {const [image, setImage ] = useState("");const [ url, setUrl ] = useState("");

useState is a react hook that lets you add react state to function components. I have two cases of use state here, one to hold image to be uploaded and the other to hold the image url after it’s been uploaded to cloudinary.

const uploadImage = () => {const data = new FormData()data.append("file", image)data.append("upload_preset", "tutorial")data.append("cloud_name","breellz")

The uploadImage function will be called once the upload button is clicked. The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent to the server. You can read more about that here.

I created a key/value pair using the append method on formData. file pointing to image. The upload_preset value is your upload preset name which I asked you to take note of while setting up your cloudinary account. Your cloud name can be found on your cloudinary dashboard. Check below for clarification.

fetch(" https://api.cloudinary.com/v1_1/breellz/image/upload",{method:"post",body: data}).then(resp => resp.json()).then(data => {setUrl(data.url)}).catch(err => console.log(err))}

Then, we make a post request to cloudinary endpoint with the body being the data. Head over to your cloudinary homepage,under account details tap more

Locate your Api base url, copy it as this is the cloudinary endpoint we’ll be making a request to. Then you add ‘/image/upload’ just like i did in the code above.

After making the request,we convert the response to json then set our url to data.url. You can log out the output to the console using

console.log(data)

This will show you the response object and you’ll see that the image url is located in the url property as shown below. You can use either the url or the secure_url property.

Then, we catch any error if there is and log it to the console.

return (<div><div><input type="file" onChange= {(e)=> setImage(e.target.files[0])}></input><button onClick={uploadImage}>Upload</button></div><div><h1>Uploaded image will be displayed here</h1><img src={url}/></div></div>)}export default App;

I created an input tag for the file upload and set the onChange attribute to setImage from our useState hook. This makes sure that whenever there’s a change ie a file gets chosen, our state is updated and image(destructured from useState) holds the new file which is found in e.target.files[0].

The onclick attribute on the button calls the function whenever the button is clicked and the image upload process begins.

Conclusion

As you can see, this is a very easy and straightforward way to handle an image upload to a server.

Leave a clap if you find this useful and feel free to leave a comment if you have any question or suggestion

Thanks for reading.

--

--