I've been working with React for the past couple of years. And in every single project, I had to use the images. After all, one image can say more than hundreds of words.
Importing and using the image in React can sound like a simple task. But sometimes, I had to spend countless hours, trying to figure out what is the problem.
I know the frustrations this can cause, and that's why I decided to write this article. After reading this article, you'll know how to import all types of images in React no matter your project setup. And on top of that, you'll learn how to optimize image loading in React.
With that being said, let's jump right into the article.
Importing Images in React
To import image in React, you need to do the following:
- Write import statement referencing the given image.
- Use imported image in the component render function.
note
I know this may sound like a straightforward process, but for it to work, certain configuration criteria needs to be met.
The configuration you need to apply depends on a couple of factors:
- Type of image you're using
- Your project setup
We'll take a closer look at each use case in the next sections.
Importing Raster Images to React
In this section, you're gonna learn how to import raster images (JPG, PNG, etc.) in React.
A raster image is a pixel-based digital image created from a matrix of pixels. It can be edited to change the color and contrast of individual pixels, but it cannot achieve the same level of detail as vector graphics or photographs.
caution
If you're using tools like CRA, NextJS or Gatsby, you don't need to modify your configuration. Instead, I suggest you to follow official documentation for handling images, depending on your toolchain.
Links to official documentation for working with images:
Importing Raster Images Using Webpack
In order to use images with Webpack, we need to specify how the images should be loaded. And to do that, we need to modify the webpack configuration.
The following configuration will treat each file with the extensions png
jpg
jpeg
or gif
as an image. And handle their import accordingly.
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.(png|jpg|jpeg|gif)$/i,
type: 'asset/resource',
},
],
},
};
When you import Image from ./image.png
, that image will be processed and added to your output directory. The Image
variable will contain the url of that image after processing.
You can import and use the image in your React component, like so.
Using image in component
import image from "./image.png";
const App = () => {
return <img src={image} alt="Image" />;
};
export default App;
If you import the image using CSS. For example, by setting it as a background property background: url('./image.png')
. The loader will recognize it as a local file and replace the url with the path to the image in your output directory.
You can import and use the image in your CSS stylesheet, like so.
Using image in CSS
.container {
background: url('./image.png');
}
Importing SVGs
Now that we know how to properly import raster images in React, let's look at the vector images.
Vector images are a lot more detailed and can be scaled to any size without loss of quality. This is because they use mathematical equations to describe the shapes in the image. This means that they do not need to be redrawn when you change the size or zoom in or out on them.
SVGs also have less data than raster images, so they load much faster.
tip
Vector images are great to use in logos and illustrations because of their adaptive sizing.
caution
If you're using tools like CRA or Gatsby, I suggest you to follow official documentation for handling SVGs, depending on your tool.
Links to official documentation for working with SVGs:
Importing SVGs Using Webpack
In order to use SVGs with Webpack, we need to install required dependencies and modify the webpack configuration.
The following configuration will treat each file with the extensions svg
as a React component. This means we can use it as such. But first, let's install dependencies.
Installing dependencies
npm install svg-inline-loader --save-dev
# or
yarn add -D svg-inline-loader
Now that we have dependencies installed, let's modify our webpack configuration.
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
module: {
rules: [
{
test: /\.svg$/,
loader: 'svg-inline-loader'
}
],
},
};
With the configuration above, you can import SVGs, and treat them as React components.
Using SVGs in React
import Image from "./image.svg";
const App = () => {
return <div><Image /></div>;
};
export default App;
Importing SVGs in NextJS
If you're using NextJS, you need to modify the configuration to load SVGs as React components. But first, start by installing dependencies.
npm install --save @svgr/webpack
# or
yarn add @svgr/webpack
When dependencies are installed, we can modify next.config.js
to use installed packages.
next.config.js
module.exports = {
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ["@svgr/webpack"]
});
return config;
}
};
note
If you don't want to touch config files and use other solutions instead, you should consider using next-image.
Concluding Thoughts
Images and videos are important aspects of any website. And as a good developer, you need to know how to handle them properly.
In this article, you learned how to import various image types in React using Webpack. On top of that, I shared with you official resources for working with images using frameworks, like NextJS, CRA, or Gatsby.
With all the information you learned. You should know how to properly import images in React, depending on your use case.
info
This article covered everything there is to know when it comes to importing images in React. If you like to learn more about images in React, and how to manage them properly. Check out our detailed guide.