Display an image from a URL / local path in React

avatar

Borislav Hadzhiev

Last updated: Apr 21, 2022

banner

Photo from Unsplash

Display an image from a URL / local path in React #

To display an image from a URL, use the img tag and set its src prop to the complete URL of the image. Optionally set the alt prop to a short description of the image.

App.js
import React from 'react'; export default function App() { return ( <div> <img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" /> </div> ); }

The example shows how to display an image from an external URL.

We used the img tag and set it's src prop to the complete URL that points to the image.

Notice that the image that is self-closing - <img />.

The alt prop helps screen readers understand what the image is about.

To display an image from a local path in React:

  1. Download the image and move it into your src directory.
  2. Import the image into your file, e.g. import MyImage from './thumbnail.webp'.
  3. Set the src prop of the image element to the imported image, e.g. <img src={MyImage} alt="horse" />.
App.js
import React from 'react'; import MyImage from './thumbnail.webp'; export default function App() { return ( <div> {/* 👇️ local image */} <img src={MyImage} alt="horse" /> {/* 👇️ external image */} <img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" /> </div> ); }

The example assumes that you have an image named thumbnail.webp in the same folder as the App component.

Make sure to specify the correct path to the image file (including the extension).

For example, if you are importing an image from one directory up, you would import as import MyImage from '../thumbnail.webp'.

The image has to be located in the src directory of your project.

Notice that in both examples we set the src prop on the img tag in order to render the image.

With images from an external URL, you set the src prop of the image to the complete URL.

With local images, you set the src proper of the img tag to the imported image.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.