How do I Reference a Local Image in React? | 2023

React is a popular front-end JavaScript library that allows developers to create dynamic and interactive user interfaces. When working with React, you may need to display images in your components. In this article, we’ll cover how to reference a local image in React.

Importing the Image

The first step in referencing a local image in React is to import it into your component. You can do this by using the import statement and assigning it to a variable:

import myImage from './myImage.png';

In this example, we’re importing an image named myImage.png from the same directory as our component.

Rendering the Image

Once you’ve imported the image, you can reference it in the src attribute of the img tag:

function MyComponent() {
  return (
    <div>
      <img src={myImage} alt="My Image" />
    </div>
  );
}

Here, we’re rendering the image using the img tag and passing the imported image variable to the src attribute. We’re also providing an alt attribute for accessibility purposes.

Dynamic Loading

Sometimes you may want to load an image dynamically based on some condition. In such cases, you can use the require function to dynamically load the image:

function MyComponent() {
  const imagePath = './myImage.png';
  return (
    <div>
      <img src={require(imagePath)} alt="My Image" />
    </div>
  );
}

Here, we’re assigning the path of the image to a variable and then using require it to load the image dynamically. This approach can be useful if you need to load different images based on some condition.

Using a Relative Path

If you don’t want to import the image, you can also use a relative path to the image file:

function MyComponent() {
  return (
    <div>
      <img src="./myImage.png" alt="My Image" />
    </div>
  );
}

Here, we’re providing a relative path to the image file in the src attribute of the img tag. This approach can be useful if you only need to reference the image once and don’t want to clutter your component with imports.

Conclusion

Referencing a local image in React is a simple process that can be done in a few different ways. You can import the image into your component, use a relative path, or dynamically load the image using require.

No matter which approach you choose, be sure to provide an alt attribute for accessibility purposes. With this knowledge, you’ll be able to easily display images in your React components.

Scroll to Top