loading...

How to Add SVG Images in React

mohammedasker profile image Mohammed Asker ・2 min read

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"

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;

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

Posted on by:

mohammedasker profile

Mohammed Asker

@mohammedasker

Front-end developer documenting my journey in coding • Anime fan • Bookworm • #100DaysOfCode challenger

Discussion

markdown guide