Programmable Media

Responsive images using JavaScript frontend frameworks

Last updated: Oct-31-2023

With Cloudinary's JavaScript frontend frameworks you can make images responsive using the responsive plugin. This causes images to resize automatically based on the viewport size. If the viewport is small, then a small image is requested, saving bytes and reducing page load times.

This video shows responsive image behavior in action. See how a new image is requested when the browser is resized, based on the configured step size:

Video Player is loading.
Current Time 0:00
Duration -:-
Loaded: 0%
Stream Type LIVE
Remaining Time 0:00
 
1x
  • descriptions off, selected
  • captions off, selected

    Make images responsive in a React app

    To use the responsive plugin in the React SDK (see below for other frameworks):

    First, install the @cloudinary/url-gen and @cloudinary/react packages:

    npm i @cloudinary/url-gen @cloudinary/react

    Then, use the responsive plugin in the AdvancedImage component, for example:

    React
    import React from 'react'
    import {Cloudinary} from "@cloudinary/url-gen";
    
    // Import the responsive plugin
    import {AdvancedImage, responsive} from '@cloudinary/react';
    
     const App = () => {
    
      // Create and configure your Cloudinary instance.
      const cld = new Cloudinary({
        cloud: {
          cloudName: 'demo'
        }
      }); 
    
      // Use the image with public ID, 'sample'.
      const myImage = cld.image('sample');
    
      // Use the responsive plugin, setting the step size to 200 pixels
      return (
        <div>
          <AdvancedImage cldImg={myImage} plugins={[responsive({steps: 200})]}/>
        </div>
      )
    };

    You can specify either the step size, as in the above example, or a set of image widths. For syntax details, see the reference.

    See this code explorer for a full working example.

    Server-side rendering of responsive images

    If you're using server-side rendering for your site, you must:

    • Use the placeholder plugin together with the responsive plugin.
    • Provide dimensions for the container element.
    • Add styling to the AdvancedImage component.

    For example:

    React
    <div style={{width: '800px'}}>
        <AdvancedImage style={{maxWidth: '100%'}} cldImg={img} plugins={[responsive(), placeholder()]}></AdvancedImage>
    </div>

    Make images responsive in other frameworks

    In addition to making images responsive in React, as shown above, you can also make them responsive in Angular, Vue and even plain JavaScript.

    Learn about other Cloudinary plugins for frontend frameworks and JavaScript:

    Note
    To automate the DPR (Device Pixel Ratio) on the browser side, use the cloudinary-core JS library.

    ✔️ Feedback sent!