MEDIA GUIDES / Image Effects

How to Resize an Image with React

resize image react

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

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:

  1. Create a free Cloudinary account — it’s free forever!
  2. Configure the React packages for the application.
  3. Upload the image to resize.
  4. 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.

“Image

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:

How to resize image with React

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.

How to resize image with react upload

Upload image and resize with react

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 image with React inside dashboard

Resize the image using one of Cloudinary’s resizing modes.

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:

Resize image with React

 

The uploaded image resized at 300 width x 200 height:

Uploaded image resized

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.

QUICK TIPS
Jen Looper
Cloudinary Logo Jen Looper

In my experience, here are tips that can help you better implement image resizing in React using Cloudinary and achieve optimal results:

  1. Select the optimal resizing mode based on context
    Cloudinary offers multiple resizing options beyond scale(), such as crop(), fill(), fit(), and pad(). Use scale for proportional resizing, fit for preserving the aspect ratio, and fill when a specific aspect ratio is required. Select pad if you want to maintain dimensions by adding background space, and crop for precise control over cropping regions. Choosing the right mode ensures that images adapt gracefully across different layouts and devices.
  2. Implement responsive images for better UX and performance
    Instead of using a single image size, create multiple versions of your images for different screen resolutions using Cloudinary’s responsive image transformations. Leverage auto breakpoints (q_auto and w_auto) to serve images optimized for varying device sizes, helping reduce file size and improve page load speed without sacrificing quality.
  3. Use lazy loading for images to optimize initial page load
    When working with React, integrate lazy loading with Cloudinary’s AdvancedImage component by setting the loading attribute to lazy. This prevents offscreen images from being loaded until the user scrolls to them, significantly boosting page performance and user experience.
  4. Combine resizing with format and quality optimizations
    While resizing reduces file size, combining it with format (f_auto) and quality (q_auto) optimization parameters can further reduce image weight while preserving visual quality. Using f_auto ensures the best format (e.g., WebP or AVIF) is selected based on browser support, and q_auto dynamically adjusts quality to maintain visual fidelity at minimal file sizes.
  5. Use conditional transformations for adaptive image styling
    For complex applications, you might need images to adjust styling based on conditions, such as user preferences or themes. Use Cloudinary’s conditional transformations with React, such as if_w_lt_500 for small screens or dynamic height adjustments based on image aspect ratios. This will allow more precise control over your images, enhancing both visual appeal and performance.
  6. Leverage named transformations for consistency
    Create named transformations within your Cloudinary account to standardize image resizing across your app. This reduces redundancy in your code and makes it easier to apply the same resizing rules to multiple images without rewriting transformations. Named transformations also simplify updates—when the transformation changes, all linked images update automatically.
  7. Use transformation chaining for combined effects
    You can combine resizing with other transformations, such as cropping, overlays, or watermarks, by chaining transformations in Cloudinary. For instance, you can resize and add a company logo in a single operation using .resize(scale().width(300)).overlay("my_logo").position("south_east"). This approach minimizes server requests and ensures images are processed efficiently.
  8. Pre-process high-resolution images for faster rendering
    When handling very high-resolution images, consider pre-processing them into smaller formats for your React app. This avoids client-side delays and reduces bandwidth usage. Use Cloudinary’s upload transformations (eager transformations) to automatically create these resized versions during the upload process, which can then be referenced dynamically in your React app.
  9. Monitor and track image usage with Cloudinary analytics
    As your app scales, use Cloudinary’s analytics tools to track which image sizes and transformations are used most frequently. This helps identify overused large image sizes, enabling you to fine-tune image resolutions for optimal performance and visual quality, particularly when dealing with a large media library.
  10. Secure your transformations with signed URLs
    For dynamic applications where transformations are applied on user-uploaded images, use signed URLs to prevent unauthorized manipulation. This adds a layer of security, ensuring only approved transformations are used, protecting your app from unexpected changes that might affect its aesthetics or performance.

By applying these tips, you can leverage Cloudinary’s image resizing capabilities in React to optimize performance, ensure visual consistency, and streamline media management across your projects.

Last updated: Nov 19, 2026
★★★★★
4.6 (20 reviews)
Talk to Sales Talk to Sales