If you want to include an image in HTML, it’s pretty straightforward. You’d enter code like this:
But including images in a React JavaScript application requires a slightly different approach.
4 Ways to Display Images in React JS
- Use the import keyword.
- Use the require keyword.
- Import SVGs directly as a React component.
- Load images directly from the network.
In this article, I will explain different ways of including images in React applications.
How to Use the Import Keyword in React to Load Images
You can import
a file right in a JavaScript module. This tells a webpack to include that file in the bundle. Your code will look like this:
This ensures that when the project is built, webpack will move the images into the build folder and provide you with correct paths.
How to Use the Require Keyword in React to Load Images
We can also use the require
keyword to load the images into your component. When you do that, your code should look like this:
require
can also be used for including audio, video or document files in your project. The most common types are .mp3, .wav, .mp4, .mov, .html and .pdf.
How to Add SVG Files to React
One way to add scalable vector graphic (SVG) files is described above, but you can also import SVGs directly as React components. In your code, it would look like this:
This is handy if you don’t want to load the SVG as a separate file. Don’t forget the curly braces in the import. The ReactComponent
import name is significant and tells Create React App
that you want a React component that renders an SVG rather than its filename.
This feature is available with [email protected]
and higher as well as [email protected]
and higher.
How to Add Network Images to React
If you are loading images from the network, then it’s a pretty straightforward approach. In your code, it would look like this:
These are the different ways to include images in your React application.