How to Display Images in React JS

How to Display Images in React JS

While building a React application, displaying images in a React application is a fundamental aspect of creating visually appealing and dynamic user interfaces. Images make web applications more attractive. If you are a developer and wondering how to display images in React JS, this blog post will help you to understand the various methods to display images in React JS, providing code examples and best practices.

1. Importing Images as Modules to Display Images in React JS

React allows you to import the images directly into your project as a module, which is one of the easiest ways to display images in your project. This method will work for those images that are part of your project and don’t change dynamically.

Example:

import React from 'react';
import logo from './assets/logo.png';

function App() {
  return (
    <div>
      <img src={logo} alt="App Logo" />
    </div>
  );
}

export default App;
 

Advantages:

  • Easy to implement.
  • Ensures the image is bundled with your app during build time.

Limitations:

  • Not suitable for dynamically loaded images.

2. Utilizing the Public Directory

You can store your images in public directory of your React project and use them directly using relevant path. This method mostly used for static images that won’t change frequently.

  • Place your image in the public/images
  • Reference it in your component:

Example:

function App() {
  return (
    <div>
      <img src={`${process.env.PUBLIC_URL}/images/example.jpg`} alt="Example" />
    </div>
  );
}

export default App;
 

Pros:

  • Does not require importing images in components.
  • Useful for static assets like logos or backgrounds.

Cons:

  • No build-time optimization or validation.

Related Topics:
What is React Router
How to create Header Component in React JS
What is state management in react

3. Dynamic Image Rendering with require()

This method is useful for cases where you want to use images dynamically based on specific conditions or from an array of data.

Example:

const images = ['image1.png', 'image2.png', 'image3.png'];

function App() {
  return (
    <div>
      {images.map((img, index) => (
        <img key={index} src={require(`./assets/${img}`)} alt={`Dynamic ${index}`} />
      ))}
    </div>
  );
}

export default App;
 

When to Use:

  • When working with multiple images or dynamic data.

Caution:

  • Avoid overusing require() as it may complicate the build process.

4. Embedding SVGs as React Components

SVGs is an image format this is also called as vector graphics that scale without losing quality. React allows you to import SVGs directly in your project as a component.

Example:

import React from 'react';
import { ReactComponent as Logo } from './assets/logo.svg';

function App() {
  return (
    <div>
      <Logo />
    </div>
  );
}

export default App;
 

Why Use SVGs?

  • Ideal for icons and scalable graphics.
  • Easy to manipulate with CSS and JavaScript.

5. Loading External Images via URLs

If you have uploaded your images on external servers or you have any image link and you want to use those images, you can directly use their URLs in the src attribute.

Example:

function App() {
  return (
    <div>
      <img src="https://example.com/path-to-image.jpg" alt="External Example" />
    </div>
  );
}

export default App;
 

Considerations:

  • Ensure the image is accessible and loading times are acceptable.
  • Handle potential CORS issues with external images.

6. Implementing Lazy Loading for Performance Optimization

Lazy loading delays the loading of images until they are visible in the viewport, improving performance.

Example:

import React, { Suspense } from 'react';
import { LazyLoadImage } from 'react-lazy-load-image-component';

function App() {
  return (
    <div>
      <LazyLoadImage
        alt="Lazy Loaded Example"
        height={300}
        src="https://example.com/path-to-large-image.jpg"
        width={400}
      />
    </div>
  );
}

export default App;
 

Advantages:

  • Reduces initial page load time.
  • Optimizes user experience on slower connections.

7. Error Handling for Image Loading Failures

Using this method, you can handle any error while image loading, it’s essential to handle the scenarios where image failed to load. You can provide a fallback image using the onError attribute.

Example:

function App() {
  const fallback = 'https://example.com/fallback.jpg';
  return (
    <div>
      <img
        src="https://example.com/nonexistent.jpg"
        alt="Example"
        onError={(e) => (e.target.src = fallback)}
      />
    </div>
  );
}

export default App;
 

Best Practices:

  • Always provide alt attributes for accessibility.
  • Use fallback images to maintain design consistency.

8. Best Practices for Image Optimization in React

  1. Optimize Image Size: Compress images using tools like TinyPNG or ImageOptim.
  2. Use Modern Formats: Prefer formats like WebP for better compression.
  3. Implement Responsive Images: Use the srcSet attribute for multiple resolutions.
  4. Leverage CDNs: Use a Content Delivery Network (CDN) for faster loading.

Conclusion

Displaying images in React is a versatile process, with multiple methods to suit various use cases. Whether you’re importing images, using the public folder, embedding SVGs, or implementing lazy loading, the choice depends on your project’s requirements. By following the best practices discussed, you can ensure optimal performance and user experience in your React applications.

For more insights and tips on React development, explore other resources on TechieTrail, your go-to platform for technical knowledge.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top