How to Display an Image from a URL in React
In React, displaying images from URLs is a common requirement when building web applications. Whether you want to display an image from an absolute URL or from a relative URL within the src
or public
folder, this article will guide you through the process.
Introduction
When working with React, there are different scenarios in which you might need to display images. You may have images stored on external servers, or you may want to include images within your project’s directory structure. In both cases, React provides straightforward ways to accomplish this.
Displaying an Image from an Absolute URL in React
To display an image from an absolute URL in React, you can use the img
element along with the src
attribute. Here’s an example:
import React from 'react';
const MyComponent = () => {
return (
<div>
<img src="https://www.example.com/images/my-image.jpg" alt="My Image" />
</div>
);
};
export default MyComponent;
In the example above, we’re directly providing the URL of the image in the src
attribute of the img
element. The alt
attribute specifies alternative text to be displayed if the image cannot be loaded.
Displaying an Image from a Relative URL in the src
Folder in React
If you have images stored within your project’s src
folder, you can import them and use them in your components. Here’s an example:
import React from 'react';
import myImage from './images/my-image.jpg';
const MyComponent = () => {
return (
<div>
<img src={myImage} alt="My Image" />
</div>
);
};
export default MyComponent;
In the example above, we import the image using the import
statement, and then use the imported variable as the src
attribute of the img
element. Make sure to adjust the path according to your project’s directory structure.
Displaying an Image from a Relative URL in the public
Folder in React
React’s public
folder is a special folder that allows you to reference assets directly. If you have images stored in the public
folder, you can reference them using their relative path. Here’s an example:
import React from 'react';
const MyComponent = () => {
return (
<div>
<img src="/images/my-image.jpg" alt="My Image" />
</div>
);
};
export default MyComponent;
In the example above, we provide the relative path to the image starting from the root of the public
folder. The leading /
indicates that the path is relative to the root.