Display great imagery, no matter your code?s style
Photo by Iwan Shimko on Unsplash.
In this article, I will explain different ways of including images in React applications. In general practice, we would include the images in HTML like this:
But including images in a React application requires a slightly different approach.
Using the import Keyword
This ensures that when the project is built, webpack will correctly move the images into the build folder and provide us with correct paths.
Using the require Keyword
We can also use the require keyword to load the images into your component. In that case, 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.
One way to add SVG files is described above. You can also import SVGs directly as React components. You can use either of the two approaches. 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.
Adding Network Images
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. See the Create React App documentation for more information.
I hope this article will help you load images in your React application. Thanks for reading.