DEV Community

Mohammed Asker
Mohammed Asker

Posted on

How to Add SVG Images in React

In this short article, I'm going to walk through a step-by-step of adding SVG images to React app. For the purpose of the article, I'm going to use Undraw which is an open-source illustration that hosts a wide variety of high quality and beautiful SVG images and you can use it for personal and commercial work.

1. Download an SVG image

First download an SVG image from the Undraw, or any other resources you like. When you finished downloading it in your computer, move the downloaded image to your project directory.

2. Import the image into the file you want to use

Here's a trick: adding SVG images is different from adding any other types of images (like PNG or JPEG). You are going to import the SVG image as if it is a component.

To do that, we'll write import like this:


import {ReactComponent as Jotaro} from "./jotaro.svg"

Enter fullscreen mode Exit fullscreen mode

In this example, I named the component Jotaro, but you can call it whatever you want. Just make sure that you are importing it from the correct file directory and wrap it with curly braces {}. As for what ReactComponent does, it basically tells React that an SVG image should be imported as a component and not a file name.

3. Add the image into your component file

Now that we've imported the image, let's actually use it.

To render the SVG image, add the Jotaro component in the component file:

import {ReactComponent as Jotaro} from "./jotaro.svg"

const App = () => (
        <div>
            <Jotaro />
        </div>
);

export default App;

Enter fullscreen mode Exit fullscreen mode

And that's it! Now you know how to add SVG images to React, you can bring SVG images into your projects. Hopefully, you find this article helpful.

You can view a complete code example from Code Sandbox with a bit of CSS styling.

Resources: Adding Images, Fonts, and Files

Top comments (4)

Collapse
 
dev_ade profile image
Adejumo Ahmad

thanks but i tried adding multiple images but its not working

Collapse
 
jashgopani profile image
Jash Gopani

Thanks a lot for this short and apt article !

Collapse
 
maxprogramming profile image
Max Programming

Thank you so much Mohammed for this article! Helped me a lot!!!

Collapse
 
ibrahimbanat profile image
Ibrahim Banat

thanks man, really helpful