As the digital landscape evolves, so does the need for dynamic and responsive web applications. React, a powerful JavaScript library, has become a cornerstone for developers looking to build high-performance user interfaces. According to Statista, as of 2023, React.js is used by 40.6% of developers worldwide, making it one of the most popular web frameworks.
In this article, we will learn the art of enhancing user experience through seamless background image transformations. We’ll explore how to handle background images in React, from simple tricks to advanced dynamic loading and manipulation techniques. Additionally, we’ll introduce you to Cloudinary, a cloud-based service that revolutionizes how we manage media assets.
In this article:
Step-by-Step Process to Change Backgrounds in React
Before we begin changing the background of our images, you’ll need to have React installed on your system. Plus, you’ll need Node version 19.9.0 or higher and npm version 9.6.3 or above. If you don’t already have Node.js, you can install it from the official Node.js website.
Since we will use Cloudinary throughout this tutorial, you need a Cloudinary account. If you don’t have one, you can sign up for free at Cloudinary.
Uploading Images to Cloudinary
Now that we have completed our requirements, let’s start by uploading our images to the Cloudinary cloud.
You can upload your images to the cloud in one of two ways: directly through the Cloudinary console or via the Cloudinary API. For now, we will examine how to upload images via the Cloudinary cloud. However, if you want to implement Cloudinary in your backend, check out their Node SDK.
To do this, head to the Cloudinary website and log in to your account. Once you’ve signed in, you’ll land on the Media Library Dashboard. Here, you can click on the Upload button to open up a file prompt:
Now, simply drag and drop an image file or click Browse to select the assets you want to upload:
Once uploaded, you can head over to the Assets tab, which shows all your images in the cloud, to verify your uploads:
Now that we’ve uploaded our assets, we need to retrieve our Cloudinary API credentials to set up our Cloudinary API in our React App. To do this, click the Programmable Media button at the top-left corner of your screen and go to the Dashboard tab. Here, you will see your Cloudinary API credentials. Copy these as we will need them later:
Creating Our React Background Changing App
Now that we’ve set up our Cloudinary cloud, let’s begin creating our React app. To do this, open up your terminal in the directory of your choosing and run the following command:
npx create-react-app background-swap
Next, we will need to install the Cloudinary React JS SDK to use Cloudinary in our app. Open up your project directory in your terminal and run the following command:
npm i @cloudinary/url-gen @cloudinary/react
Now open up your project in your preferred IDE, and open up App.js
, which is located in the src
directory of your project. You will find that React has already generated a basic JavaScript structure for your app. We won’t be needing this, so go ahead and copy and paste the following code into your file:
import React from 'react' import {Cloudinary} from "@cloudinary/url-gen"; const App = () => { // Create a Cloudinary instance and set your cloud name. const cld = new Cloudinary({ cloud: { cloudName: 'your_cloud_name', api_key: 'your_api_key', api_secret 'your_api_secret' } }); }; export default App;
Here, we simply import the Cloudinary React JS SDK and define our Cloudinary API. Make sure to replace your_cloud_name
, your_api_key
, and your_api_secret
with your actual Cloudinary credentials.
With our API setup complete, we can begin changing the backgrounds of our images.
Advanced Background Changing Techniques in React
Background changing, as the name implies, involves replacing the existing background of an image with something entirely new. This is a popular tool in photo editing and graphic design, allowing you to create new scenes, enhance focus on specific elements, or add creative flair. However, many free tools are time-consuming and don’t offer the precision and accuracy necessary to create appealing images.
Cloudinary leverages AI to intelligently identify the foreground object in your image. This allows for cleaner and more precise background removal compared to manual methods. Let’s take a look at how we can use Cloudinary’s AI to change the background of our Images.
Before we begin, we will first need to import the necessary modules and retrieve an image from the Cloudinary cloud:
import React from 'react'; import { AdvancedImage } from '@cloudinary/react'; import { Cloudinary } from "@cloudinary/url-gen"; import { backgroundRemoval } from "@cloudinary/url-gen/actions/effect"; import { scale } from "@cloudinary/url-gen/actions/resize"; import { source } from "@cloudinary/url-gen/actions/underlay"; import { image } from "@cloudinary/url-gen/qualifiers/source"; import { Position } from "@cloudinary/url-gen/qualifiers/position"; import { Transformation } from "@cloudinary/url-gen"; ...
Next, we will define the public ID of our image and use Cloudinary’s image method to retrieve an image from our cloud:
// Image from which background needs to be removed const myImagePublicId = 'docs/model.jpg'; const myImage = cld.image(myImagePublicId);
Here, we use docs/model
available in Cloudinary’s demo cloud.
Now, we will define the transformation to be applied to our image:
myImage.addTransformation( new Transformation().effect(backgroundRemoval()).resize(scale().width(800)).underlay(source(image("docs/bench-house.jpg")).position(new Position().offsetY(-10))));
Here, we are using Cloudinary’s AI background removal tools to remove the background of our image. Next, we use the .resize()
method to scale and resize the image. Then, we use the .underlay()
method and add the bench-house
image as the background of our image. Finally, we use the .position()
method to adjust the position of our top image.
Finally, we return the image to Cloudinary’s AdvancedImage
component:
return ( <div> <AdvancedImage cldImg={myImage} controls /> </div> );
Here is what our complete App.js
file looks like:
import React from 'react'; import { AdvancedImage } from '@cloudinary/react'; import { Cloudinary } from "@cloudinary/url-gen"; import { backgroundRemoval } from "@cloudinary/url-gen/actions/effect"; import { scale } from "@cloudinary/url-gen/actions/resize"; import { source } from "@cloudinary/url-gen/actions/underlay"; import { image } from "@cloudinary/url-gen/qualifiers/source"; import { Position } from "@cloudinary/url-gen/qualifiers/position"; import { Transformation } from "@cloudinary/url-gen"; const App = () => { // Create a Cloudinary instance and set your cloud name. const cld = new Cloudinary({ cloud: { cloudName: 'your_cloud_name', api_key: 'your_api_key', api_secret 'your_api_secret' } }); // Image from which background needs to be removed const myImagePublicId = 'docs/model.jpg'; const myImage = cld.image(myImagePublicId); myImage.addTransformation( new Transformation().effect(backgroundRemoval()).resize(scale().width(800)).underlay(source(image("docs/bench-house.jpg")).position(new Position().offsetY(-10)))); return ( <div> <AdvancedImage cldImg={myImage} controls /> </div> ); }; export default App;
Finally, open your terminal and start your React application with npm start
Here is what our image looks like:
Wrapping Up
While traditional methods involve integrating separate libraries for image manipulation and management, Cloudinary offers a more streamlined solution. Its easy integration with React allows you to directly utilize their extensive image manipulation library within your React components. This includes background removal and replacement options, access to a vast library of overlays and effects, and the ability to dynamically adjust image properties.
This approach simplifies development and ensures consistent visuals across tons of different browsers and devices. Cloudinary handles all image manipulation on its servers, guaranteeing compatibility and high-quality output. Additionally, by offloading image processing to the cloud, you can improve the performance of your React app, allowing you to focus on building engaging user interfaces.
Unleash the power of Cloudinary in your React projects! Sign up for a free account and explore its comprehensive image manipulation features for React development.
More from Cloudinary:
How to Automatically Remove Photo Backgrounds in Seconds With AI