DEV Community

JsConfig
JsConfig

Posted on

Different ways of using Images in ReactJs

In React, pictures make your app look cool! This guide will show you easy ways to use different types of images. Whether they're from your computer, change when you click, or load super fast, we'll learn simple tricks to make your React app awesome.

Local Charm: Importing Images

1.1 Importing Local Images:

The easiest way to use images stored within your React project is by importing them directly into your components. Imagine having a folder named 'images' with your local gems:

import localImage from './images/local-gem.jpg';

const LocalImageComponent = () => {
  return <img src={localImage} alt="Local Gem" />;
};
Enter fullscreen mode Exit fullscreen mode

Distant Dreams: Hosted Images

2.1 Including Images from URLs:

Easily include images from external URLs to add a touch of the web to your project:

const HostedImageComponent = () => {
  return <img src="https://example.com/web-image.jpg" alt="Web Image" />;
};
Enter fullscreen mode Exit fullscreen mode

Dynamic Delights: Loading Images Dynamically

3.1 Dynamically Loading Images:

When your images need to change dynamically based on conditions or data, React has your back:

const DynamicImageComponent = ({ imageIndex }) => {
  const imageArray = ['url1.jpg', 'url2.jpg', 'url3.jpg'];
  const dynamicImage = imageArray[imageIndex];

  return <img src={dynamicImage} alt="Dynamic Gem" />;
};
Enter fullscreen mode Exit fullscreen mode

SVG Stories: Reacting to SVGs

4.1 Using SVGs in React:

SVGs, the heroes of vector graphics, find a cozy home in React components:

import { ReactComponent as Logo } from './images/logo.svg';

const SvgImageComponent = () => {
  return (
    <div>
      {/* Using an imported SVG */}
      <Logo />

      {/* Using an inline SVG */}
      <svg width="100" height="100" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="40" fill="green" />
      </svg>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

Performance Pilots: Optimizing for Speed

5.1 Lazy Loading Images:

For a smoother user experience, consider lazy loading images not immediately visible on the screen:

const LazyLoadImage = () => {
  return <img src="lazy-gem.jpg" alt="Lazy Gem" loading="lazy" />;
};
Enter fullscreen mode Exit fullscreen mode

Images in React are not just visuals; they're the heroes of your story. With these easy tricks, you're all set to make your React app a visual masterpiece. Try them out, mix things up, and enjoy your journey with React! Happy coding! ๐Ÿš€๐Ÿ“ธ
This tutorial is brought to you by Jsconfig.com, specializing in Next.Js training.

Feel free to contribute any additional methods you're familiar with in the comment section.

Top comments (0)