Table of Contents
In this article, we will see the recommended way to import local images into a react component and display them. We will also see how to display remote images and images as a background.
Project setup
First, create a react app using the following command:
1npx create-react-app react-images
Add the following styles to index.css
, so that the image appears in the center of the screen:
1.App {2 height: 100vh;3 display: flex;4 justify-content: center;5 align-items: center;6 gap: 12px;7}
Including remote images
Including remote image is like how we include images in normal HTML pages:
1function App() {2 return (3 <div className="App">4 <img5 src="https://codingdeft-images.s3.amazonaws.com/public/img/posts/react-include-images/lake.jpg"6 alt="lake"7 width={640}8 height={427}9 />10 </div>11 )12}1314export default App
Always ensure that you provide:
- an
alt
property, which describes the image and helps in accessibility and SEO. width
andheight
properties, which help in avoiding Cumulative Layout Shifts, which in turn provides better user experience and boosts SEO.
Including local images
Your first guess to include a local image would be to place it in the current directory,
or in a folder called images
and refer to it as shown below:
1<img src="./lake.jpg" alt="lake" width="{640}" height="{427}" />
This approach would not work, because here we are referring to the image file as ./lake.jpg
,
which means we are trying to find lake.jpg
in the current directory.
However, in react, the current directory (in this case) is public
directory and we do not have lake.jpg
there.
One way to fix this is to move lake.jpg
to public
directory.
But the recommended approach is to import the image like a component, as shown below:
1import lake from "./lake.jpg"23function App() {4 return (5 <div className="App">6 <img7 src="https://codingdeft-images.s3.amazonaws.com/public/img/posts/react-include-images/lake.jpg"8 alt="lake"9 width={640}10 height={427}11 />12 <img src={lake} alt="lake" width={640} height={427} />13 </div>14 )15}1617export default App
If you inspect the browser, you will see that the image URL is something similar to the one shown below:
Each time the application is built, the URL will be unique and this will ensure that if the image changes, the latest image is loaded for the users who have previously visited the site and haven't cleared their browser cache.
Including background images
If you want to include the image as a background image, you can use the following code:
1import lake from "./lake.jpg"23function App() {4 return (5 <div className="App">6 <div7 style={{ backgroundImage: `url(${lake})`, width: 640, height: 427 }}8 ></div>9 </div>10 )11}1213export default App
Do follow me on twitter where I post developer insights more often!