Borislav Hadzhiev
Sun May 01 2022·2 min read
Photo by Tyler Scheviak
To import and use an image in a React component:
import MyImage from './thumbnail.webp';
.src
prop on the img
element.<img src={MyImage} alt="horse" />
.// 👇️ import the image 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> ); }
We used an ES6 default import to import an image in a React application.
The alt
prop helps screen readers understand what the image is about.
Notice that the image that is self-closing - <img />
.
The example assumes that you have an image named thumbnail.webp
in the same
folder as the App
component.
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.
You can use this approach to import and use png
, svg
, webp
, jpg
, etc,
images in your React app.
// 👇️ import SVG image import MyImage from './logo.svg'; export default function App() { return ( <div> {/* 👇️ local image */} <img src={MyImage} alt="logo" /> {/* 👇️ external image */} <img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" /> </div> ); }
If your images are located in the public
directory, use an absolute path
when setting the src
prop on the img
element.
For example, if you have an image located at public/images/thumbnail.webp
, you
would set the src
of the img to "/images/thumbnail.webp"
.
export default function App() { return ( <div> {/* 👇️ local image */} <img src="/images/thumbnail.webp" alt="horse" /> {/* 👇️ external image */} <img src="https://bobbyhadz.com/images/blog/react-prevent-multiple-button-clicks/thumbnail.webp" alt="car" /> </div> ); }
If you aren't able to use the ES6 import/export syntax in your setup, try using
require()
.
export default function App() { return ( <div> {/* 👇️ local image */} <img src={require('./thumbnail.webp')} alt="horse" /> <img src={require('./logo.svg').default} alt="horse" /> </div> ); }
The example above uses the require()
syntax to import 2 images located in the
same directory as the App
component.
If you need to display an image from an external URL, set the src
prop on the
img
tag to the complete URL of the image.
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.