Add animated SVG to React websites

Updated: Mar 2, 2023


There are multiple React frameworks that you can use for your website. Whether it's client or server-side rendered, there are lots of different solutions that you can use to add animated SVG.

In case your SVG is animated on mouse over, you must add it as Inline SVG. You will see how this works in the following examples:


I.) React websites based on Create React App


To add an animated SVG to your Create React App project, you need to construct a custom component on the top of the file exported.

Check & test how the end result will look like & work in our github example.

Step 1.) Add SVG:

Add the exported SVG into your project - stopwatch.svg in the example below.


Step 2.) Create Custom Component:

Add your wrapper component (Stopwatch.jsx in this example) with the structure below:

/* eslint-disable */

import { useEffect } from "react";
import { ReactComponent as Svg } from "./stopwatch.svg";

export default function Stopwatch() {
  useEffect(() => {
  // ... javascript goes here 
  // !function ... long code 
  }, []);
  return (
      <Svg/>
  )
}
Stopwatch.jsx

Step 3.) Move Javascript Code:

Importing the static part of the SVG works as described in the CRA documentation (using ReactComponent), however to make the animation fully work, the Javascript code has to be moved from the exported svg (stopwatch.svg) into useEffect method of the custom component (Stopwatch.jsx).

Open the SVG file with an editor, cut the code between script tags:

<script><![CDATA[…….code……]]></script>

Paste the code in the useEffect hook of the custom component. After you have removed the Javascript, just delete the  empty remaining tags from the SVG file:

<script><![CDATA[]]></script>

You also need to add the linting directive at the top of the custom component:

/* eslint-disable */

because the Javascript is minified and it will create a lot of code styling errors. Do not try to format the Javascript, otherwise line wrapping can make it stop working.


Step 4.) Handle Style Tags:

Also to be noted that if your animated SVG has a style tag (i.e. a specific font has been used), the CDATA wrapper (starting <![CDATA[ and ending ]] tags) needs to be deleted from that as well; so, this format:

<style><![CDATA[……data……]]></style>

Has to become this one:

<style>……data……</style>

Now just import your SVG file and return it in the function.

Also import your component where you want to use your SVG.

Now you should have a working animated SVG.


II.) React websites based on Vite

In order to have the same method working for Vite as described above You need to install the vite-plugin-svgr plugin.

One can install it by running the following command (from the project's main directory):

# with npm
npm i vite-plugin-svgr

# with yarn
yarn add vite-plugin-svgr

Next, add the plugin inside your app's vite.config.js:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import svgr from "vite-plugin-svgr";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [svgr(), react()],
});

Now, one can import the SVG files as React Components:

import { ReactComponent as Svg } from "./stopwatch.svg";

The rest of the steps are the same as described above, under I.) React websites based on Create React App.


III.) React websites using Webpack


Client based React apps are mostly using Webpack to bundle all the dependencies into a single file. You can use multiple plugins for loading files by specifying their path using include or exclude keys, as shown in this Webpack documentation.

Webpack has a loader for handling SVG that's called file-loader. There are a couple of ways to make this work. We'll start with the method created by Webpack.


Method (1)


Let's install it.

npm install file-loader --save-dev

Add the configuration to webpack.config.js file.

      {
        test: /\.(png|jpe?g|gif|svg)$/i,
        use: [
          {
            loader: 'file-loader',
          },
        ],
      },

Now you can simply import SVG files and use them.

import React from 'react';
import Animated from './Animated.svg';

function App() {
  return (
    <object type="image/svg+xml" data={Animated}>svg-animation</object>
  );
}
export default App;

Method (2)


Import SVG using svg-react-loader -  "A webpack loader allowing for inline usage of a SVG as a React component" as mentioned on the github page.

Install.

npm install --save-dev svg-react-loader

Add its configuration to webpack.config.js

      {
        test: /\.svg$/,
        exclude: /node_modules/,
        use: {
          loader: 'svg-react-loader',
        },
      }

The react component looks like this.

import React from 'react';
import Animated from './Animated.svg'

const MyComponent = () => (
    <Animated />
)

export default MyComponent
Also find our test repository here (following this guide to set up React with Webpack).

Also find our test repository here (following this guide to set up React with Webpack).

IV.) Gatsby websites


SVGator/gatsby-svg
This is a sample project of how to add an animated SVG to a Gatsby website. - SVGator/gatsby-svg
Gatsby example

Here we can use gatsby-plugin-react-svg a plugin based on svg-react-loader.

Just install it.

npm install --save gatsby-plugin-react-svg

Add config to gatsby-config.js.

plugins: [
  {
    resolve: "gatsby-plugin-react-svg",
    options: {
      rule: {
        include: /assets/ // Where the animated svgs are.
      }
    }
  }
];

Import SVG.

import React from 'react';
import Animated from '../assets/Animated.svg'

const MyComponent = () => (
    <Animated />
)

export default MyComponent

V.) Next.js websites


Next supports SVG out of the box. Just add your svg to the public folder, as explained in Next.js'  documentation, and use it in the object tag like so:

const Index = () => (
 <div>
  <object type="image/svg+xml" data="/animated.svg">svg-animation</object>
 </div>
);

export default Index;

See a working example here.

More articles:

Add animated SVG to React Native

Add animated SVG to WordPress

Add animated SVG to your website


We hope this helps.

In case you know different ways to import animated SVG or you've got questions, just send us an email to contact@svgator.com and we will get back to you as soon as we can.