Key takeaways:
- CSS width and height only change how big an image looks. The browser still downloads the full file, so resize on the server or with a service when file size matters.
- Use scale to keep the aspect ratio, and fill with automatic gravity when the image must fit an exact box without distortion.
- Create React App is deprecated, so this guide now sets up the project with Vite, which reads environment variables that start with VITE_.
Resizing means making an image smaller or larger without cropping or cutting out parts of the image. Resizing alters an image’s dimensions, typically affecting its file size and quality.
There are many reasons to resize an image. The most common is to reduce the image file size, making large images easier to email or share online. For developers, usually it’s done to ensure the images render properly on various devices and screen sizes when building a responsive website or web application.
In this article, we will walk through how to resize an image with React, a JavaScript library for building user interfaces. This article will use React packages that contain the image transformation features of a platform called Cloudinary to consistently deliver images to the browser at the requested size.
Cloudinary is a visual media platform used to upload, store, manage, transform, and deliver images and videos for websites and applications. The platform also offers a vast collection of SDKs for frontend frameworks and libraries. With Cloudinary, you can organize your media assets and automatically generate optimized assets through unique links.
In this article:
- Sandbox
- Using the Cloudinary React packages
- Configuring Cloudinary in our React application
- Uploading images to Cloudinary
- Resize an image with React using Cloudinary
- CSS, Canvas or Cloudinary: How Should You Resize Images in React?
Sandbox
This project was completed in a CodeSandbox. Fork and run it to quickly resize an image with React.
<CodeSandbox id="summer-leaf-14y5pp" title="How to resize image with React" />
View the codebase on GitHub here.
Using the Cloudinary React packages
To get started and resize an image with React:
- Create a free Cloudinary account — it’s free forever!
- Configure the React packages for the application.
- Upload the image to resize.
- Resize the image using the Cloudinary resize modes.
Configuring Cloudinary in our React application
After creating a Cloudinary account:
1. Create a React application by navigating to a directory and running the below command in a terminal:
npm create vite@latest resize_image -- --template react && cd resize_image && npm install
The above command creates a React application called resize_image and navigates to the project directory.
2. Install the @cloudinary/url-gen and @cloudinary/react packages with:
npm i @cloudinary/url-gen @cloudinary/react
The @cloudinary/url-gen package includes all the functionalities needed to create delivery urls for the images.
The @cloudinary/react package includes the React components for rendering, configuring, and transforming the images.
3. Create a .env file in the root directory. Include the cloud name given during sign-up as an environment variable in order to use the Cloudinary components. Get the cloud name by logging into the Cloudinary console and viewing any of the highlighted sections as shown below:
In the file, add the variable below:
VITE_CLOUDINARY_CLOUD_NAME=YOUR_CLOUD_NAME
Now that we have finished the configuration process, it’s time to upload and resize an image with React.
Uploading images to Cloudinary
There are multiple ways we can upload images to Cloudinary. In this article, we will use the Upload widget. To upload an image using the Upload widget, click on Media Library and then click Upload.
After uploading the image, get the image Public ID (the unique identifier for an asset stored in Cloudinary), as highlighted below. This is the ID we will use and resize:
Resize the image using one of Cloudinary’s resizing modes.
Pro Tip!Consider Cloudinary’s Digital Asset Management
Looking for a centralized location to manage all your media assets? Cloudinary’s Media Library makes it easy to upload, store, manage, and deliver images and videos efficiently.
Resize an image with React using Cloudinary
Cloudinary provides many resizing and cropping modes, including scale, fit, fill, pad, crop and thumb. You can view all of the modes in the Cloudinary Documentation.
For this post, we will use the scale resizing mode.
Using scale resizing mode
To use the scale resizing mode to resize an image with React, we must first import the Cloudinary packages, the Cloudinary AdvancedImage component, and the required scale action.
In the src/App.jsx file of the React application, add:
import { Cloudinary } from "@cloudinary/url-gen";
import { AdvancedImage } from "@cloudinary/react";
// Import required action.
import {scale} from "@cloudinary/url-gen/actions/resize";
The AdvancedImage component creates an image by passing the generated Cloudinary image url.
Instantiate Cloudinary and pass a cloud name to use the Cloudinary packages and components.
Then, in the App.js file, add:
const App = () => {
const cld = new Cloudinary({
cloud: {
cloudName: import.meta.env.VITE_CLOUDINARY_CLOUD_NAME
}
});
return ();
}
export default App;
Create a variable that will use the cld instance with the image Public ID to generate the image url:
const imageToResizeToSpecifiedDimension = cld.image("<image_publicId>");
Use scale to resize the image:
imageToResizeToSpecifiedDimension.resize(scale().width(300))
In the return (); function, add the JSX to display the image on the browser using the Cloudinary AdvancedImage component.
return (
<div>
<AdvancedImage cldImg={imageToResizeToSpecifiedDimension} />
</div>
);
Resizing results
The uploaded image at 870 width x 580 height before resizing:
The uploaded image resized at 300 width x 200 height:
How Do You Resize to an Exact Size Without Distortion?
scale changes the width and keeps the aspect ratio, which is why the 870 x 580 image above becomes 300 x 200. When a layout needs an exact box, such as a 300 x 300 avatar, use fill with automatic gravity instead: Cloudinary resizes the image to cover the box and crops the rest, keeping the most important part of the picture in frame. Adding f_auto and q_auto, and the lazyload and responsive plugins, keeps the download small:
import { Cloudinary } from "@cloudinary/url-gen";
import { AdvancedImage, lazyload, responsive } from "@cloudinary/react";
import { fill } from "@cloudinary/url-gen/actions/resize";
import { autoGravity } from "@cloudinary/url-gen/qualifiers/gravity";
import { format, quality } from "@cloudinary/url-gen/actions/delivery";
import { auto } from "@cloudinary/url-gen/qualifiers/format";
import { auto as autoQuality } from "@cloudinary/url-gen/qualifiers/quality";
const cld = new Cloudinary({
cloud: { cloudName: import.meta.env.VITE_CLOUDINARY_CLOUD_NAME },
});
export default function Avatar({ publicId }) {
const img = cld
.image(publicId)
.resize(fill().width(300).height(300).gravity(autoGravity()))
.delivery(format(auto()))
.delivery(quality(autoQuality()));
// .../image/upload/c_fill,g_auto,h_300,w_300/f_auto/q_auto/<publicId>
return <AdvancedImage cldImg={img} plugins={[lazyload(), responsive()]} />;
}
The lazyload plugin delays the request until the image is near the viewport, and responsive picks a width that matches the container, so a phone does not download the desktop size.
CSS, Canvas or Cloudinary: How Should You Resize Images in React?
There are three common ways to make an image smaller in a React app, and they do very different things:
| Feature | CSS (width, height, object-fit) | Canvas (drawImage, toBlob) | Cloudinary URL transformations |
|---|---|---|---|
| What changes | Only the displayed size | The actual pixels, in the browser | The actual pixels, on Cloudinary’s servers |
| File the user downloads | The full original | Whatever you upload or display after resizing | A resized, optimized file |
| Formats | Unchanged | Whatever toBlob supports in that browser | f_auto picks the best format per browser |
| Best for | Fitting already small images into a layout | Shrinking user photos before upload | Delivering images at many sizes from one original |
Many apps combine two of them: canvas to cut huge phone photos down before upload, and Cloudinary to deliver each size the interface needs.
Frequently Asked Questions
How do you resize an image in React?
For display only, set width and height in CSS or on the img element. To actually reduce the file, resize it before it reaches the browser. With Cloudinary, build the image with cld.image(publicId).resize(scale().width(300)) from @cloudinary/url-gen and render it with the AdvancedImage component from @cloudinary/react, which requests the smaller version.
How do you keep the aspect ratio when resizing?
Give only one dimension. In Cloudinary, scale().width(300) sets the width and calculates the height from the original proportions. In CSS, set the width and leave the height as auto, or use the aspect-ratio property. When you need both dimensions exactly, use fill with automatic gravity, which crops instead of stretching.
Does resizing an image with CSS reduce its file size?
No. CSS changes how large the image appears, but the browser downloads the original file first and then scales it on screen. A 4000 px photo displayed at 300 px still costs the full download. To reduce the bytes, deliver a smaller file, for example with a Cloudinary resize transformation or responsive images using srcset.
What is the difference between scale and fill?
scale resizes the whole image to the dimensions you give and keeps its proportions when you set one side. fill makes the image cover the exact width and height you request and crops whatever does not fit. Pair fill with automatic gravity so Cloudinary keeps the most important part of the image in the crop.
