MEDIA GUIDES / Web Performance

5 Ways to Import Images in React + Bonus Automation Method

import images in react

Working with Images in React Applications 

React, a JavaScript library for creating user interfaces, simplifies image management. One way to do this is by importing images, which lets developers treat images as React modules. This approach enables you to import an image into a component in the same way you would with a JavaScript module. It provides better control over your images and can help optimize your app’s performance.

React’s image handling capabilities also include support for SVGs and externally hosted images. SVGs, or Scalable Vector Graphics, are XML-based vector images that can be scaled without losing quality. They are preferred for logos, icons, and illustrations. Externally hosted images are images stored on a server different from your application. React allows you to render these images while saving storage space and bandwidth

This is part of a series of articles about image optimization.

In this article:

5 Ways to Import Images in React 

React’s component-based architecture provides a versatile approach to managing assets, helping you build visually appealing and performance-efficient applications. Whether you’re enhancing your user interface with striking graphics or crafting an engaging user experience with images, knowing the different ways to import images in React is essential.

Before you begin, create a sample React application using the following syntax:

npx create-react-app image-display-app

Importing and Using an Image in a React Component

The simplest method to import an image in React is by directly importing it into your component file, provided the image is stored within your project directory.

Here’s a code snippet that demonstrates this:

import React from 'react';
import myImage from './path_to_your_image.png';
const MyComponent = () => {
  return (
    <div>
      <img src={myImage} alt="My Image" />
    </div>
  );
};

export default MyComponent;

In the code above, we import an image file named “myImage” from a specified path. Our component’s render method uses the image within the img tag. The img tag’s src attribute is set to the imported image, and the alt attribute is used to provide a text alternative for the image.

The path to your image file should be relative to the file you’re importing. Specify the image filename if the image is in the same directory as the component file.

import images in react

Importing an SVG Image in Your React Application

Importing an SVG (Scalable Vector Graphics) image in a React application differs from importing a standard image file. SVG images are XML-based vector graphics, which can be scaled indefinitely without losing quality, making them ideal for various web applications.

Here’s a code snippet demonstrating how to import an SVG image:

import React from 'react';
import { ReactComponent as MyLogo } from './my_logo.svg';
const MyComponent = () => {
  return (
    <div>
      <MyLogo />
    </div>
  );
};

export default MyComponent;

In the above example, we import an SVG image using the ReactComponent syntax. This allows us to use the SVG image as a React component. We can then render the SVG image by simply calling MyLogo in our component’s render method.

Importing an Image from the Public Directory

Sometimes, you might need to import an image located in your React application’s public directory. This directory is typically used for assets that will remain static and won’t be processed by Webpack.

To use an image from the public directory, you don’t need to import it. Instead, you can reference it directly in your component.

import React from 'react';
const MyComponent = () => {
  return (
    <div>
      <img src={'/public/path_to_your_image.png'} alt="My Image" />
    </div>
  );
};

export default MyComponent;

In the code above, we specify the path to the image in the src attribute of the img tag. The path should start with /public and should be relative to the public directory. Or you can use the following constant:

<img src={process.env.PUBLIC_URL + '/image.jpg'} alt="My Image" />

Importing an Image with the require() Function

Another method to import images in React is by using the require() function. This method is especially useful when the path to your image is dynamic and needs to be constructed at runtime.

Here’s an example:

import React from 'react';
const MyComponent = () => {
  const imagePath = './path_to_your_image.png';
  return (
    <div>
      <img src={require(\ "./yourimage.png")} alt="My Image" />
    </div>
  );
};

export default MyComponent;

In the above code, the require() function is used to import the image file. The path to the image file is specified as a string in the imagePath variable. This path can be dynamically based on your application’s state or props.

Rendering an Externally Hosted Image

Let’s see how you can render an externally hosted image in your React application. This situation may arise when your images are hosted on a CDN (Content Delivery Network) or another external server.

Here’s how you can do it:

import React from 'react';

const MyComponent = () => {
  const imageUrl = 'https://example.com/path_to_your_image.png';
  return (
    <div>
      <img src={imageUrl} alt="My Image" />
    </div>
  );
};

export default MyComponent;

Maximizing Your Images with React and Cloudinary

React’s component-driven architecture is favored for creating dynamic, responsive web applications. Cloudinary’s React SDK simplifies the process, enabling you to fetch, display, and manage images and videos directly within React components. This integration enhances your workflow, allowing you to apply real-time transformations and optimizations to your media assets with minimal coding effort.

Let’s put this into practice with a quick tutorial on applying basic image edits using Cloudinary within a React application.

Step 1: Setting Up Your Cloudinary Account

First off, if you haven’t already, sign up for a free Cloudinary account. Once you’re set up, locate your Cloudinary cloud name, API key, and API secret from your dashboard; you’ll need these for integrating Cloudinary with your React project.

Install the Cloudinary React SDK by running:

npm install cloudinary-react

In your React component, import the Image component from cloudinary-react:

import { Image } from 'cloudinary-react';

Step 2: Displaying an Image

To display an image stored in your Cloudinary account, use the Image component and specify the cloudName and publicId props:

<Image cloudName="your_cloud_name" publicId="sample_image" width="300" crop="scale" />

Step 3: Applying Transformations

Now for the fun part – applying transformations. Let’s say you want to resize the image, apply a sepia effect, and add a text overlay. Simply chain the transformations in the publicId prop:

<Image cloudName="your_cloud_name" publicId="sample_image_w_300,h_300,c_fill,e_sepia,l_text:Arial_60:Hello" />

And voilà! You’ve just applied real-time image transformations with Cloudinary in your React app.

By integrating Cloudinary into your React projects, you leverage a powerful solution for managing and optimizing your media assets and ensure your applications remain engaging, responsive, and high-performing across all devices. Whether you’re building a simple portfolio or a complex e-commerce site, Cloudinary’s seamless integration with React empowers you to deliver top-notch visual experiences without compromising speed or performance.

Learn more in Cloudinary’s React quick start guide

QUICK TIPS
Tamas Piros
Cloudinary Logo Tamas Piros

In my experience, here are tips that can help you better manage and import images in React, ensuring optimal performance and maintainability:

  1. Use relative imports for easy maintenance
    When importing images in React components, prefer using relative imports over absolute paths. This keeps your codebase maintainable, especially when moving components or refactoring file structures. Relative paths are easier to track and update during project changes.
  2. Leverage dynamic imports with require() for flexible image handling
    When dealing with dynamic images that change based on user interaction or data, use the require() function to dynamically import images at runtime. This approach is useful in scenarios like product galleries, where image paths might be generated based on user choices or backend data.
  3. Optimize SVGs by importing them as components
    SVGs are vector-based and ideal for icons or logos. Import SVGs directly as React components using the ReactComponent syntax. This allows you to manipulate SVG attributes (like fill, stroke, or size) directly in your JSX, providing more flexibility than traditional image formats.
  4. Utilize the public directory for static assets
    For images that don’t change often and need to be publicly accessible (like logos or background images), store them in the public directory. This ensures they are served directly by the server without being processed by Webpack, improving load times for these assets.
  5. Preload critical images to enhance perceived performance
    Preload images that are critical to your app’s initial view using the <link rel="preload"> tag in your HTML or by using the Image constructor in JavaScript. This can reduce perceived load times by ensuring that key images are available immediately when needed.
  6. Consider lazy loading for non-critical images
    Use lazy loading to defer the loading of images that aren’t immediately visible on the screen. This improves initial page load times and reduces bandwidth usage. React’s React.lazy and Suspense can help you implement lazy loading for image-heavy components.
  7. Integrate Cloudinary for real-time image transformations
    For advanced image management, integrate Cloudinary’s React SDK. Cloudinary allows you to serve images in different sizes, formats, and quality levels based on user device and connection speed, enhancing performance and user experience. Use Cloudinary’s transformation URL API to apply effects like cropping, resizing, or overlays on the fly.
  8. Use WebP format for better compression
    Where possible, serve images in WebP format, which offers superior compression compared to JPEG or PNG without losing quality. You can automate the conversion of images to WebP using tools like Cloudinary, ensuring that users always get the most optimized image format.
  9. Handle external images carefully
    When rendering externally hosted images, ensure the URLs are reliable and secure (prefer HTTPS). Consider using a service like Cloudinary to cache and optimize these images, improving load times and reducing the impact of external server performance on your app.
  10. Cache images with service workers
    Use service workers to cache images in your React Progressive Web App (PWA). This reduces network requests and speeds up subsequent page loads, particularly in offline scenarios. Service workers allow your app to serve cached images instantly, enhancing the user experience.

These tips will help you effectively manage images in React, ensuring that your application is performant, visually appealing, and easy to maintain.

Last updated: May 2, 2025