How to Add Animated SVG to React Websites | SVGator Help (2024)

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/> )}

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 npmnpm i vite-plugin-svgr# with yarnyarn 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

How to Add Animated SVG to React Websites | SVGator Help (1)GitHubSVGator

How to Add Animated SVG to React Websites | SVGator Help (2)

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.

How to Add Animated SVG to React Websites | SVGator Help (2024)

FAQs

How to add an animated SVG to React? ›

I.) React websites based on Create React App
  1. Step 1.) Add SVG: Add the exported SVG into your project - stopwatch. ...
  2. Step 2.) Create Custom Component: Add your wrapper component ( Stopwatch.jsx in this example) with the structure below: ...
  3. Step 3.) Move Javascript Code: ...
  4. Step 4.) Handle Style Tags:
Mar 2, 2023

How do I add SVG to React Project? ›

You can add it to your project by running the command $ npm install svg-url-loader --save-dev .

How to make SVG responsive in React? ›

In React, you can make an SVG image responsive by controlling its width and height using CSS. To make an SVG image responsive, you first need to ensure that the SVG has a viewBox attribute. The viewBox attribute specifies the aspect ratio and coordinate system of the SVG, allowing it to scale correctly.

How to use dynamic SVG in React? ›

We can use inline SVG directly in React components by including the SVG code as a distinct <svg> element. It involves embedding the SVG markup directly within the JSX code of a React component. In this example, we directly embed a sample SVG element into the App component.

How do I import SVG animations? ›

You can use one of the following options to import SVG files in to Animate:
  1. Using the File Import option: Click File > Import > Import to Stage, or Import to Library and select the SVG file.
  2. Drag and drop an SVG file directly on to the stage.
Feb 11, 2022

How to use SVG in a TS file? ›

How to use svg-to-ts
  1. Binaries. ...
  2. Configuration. ...
  3. Passing arguments to the binary. ...
  4. Configure svg-to-ts over package. ...
  5. Configuration file. ...
  6. Converting to a single object ( conversionType==='object' ) ...
  7. Multiple constants - Treeshakable and typesafe with one file ( conversionType==='constants' )
Feb 18, 2024

How to convert SVG to React component? ›

Using SVGR in the command line

Then, we call SVGR in the command-line, passing in the . svg file and other flags to replace different attributes with our own values. The above command will take our logo. svg file and convert it to a React component.

How do I import SVG into React next JS? ›

Your code
  1. import Star from './star.svg' const Example = () => ( <div> <Star /> </div> )
  2. import Image from 'next/image' import starUrl from './star.svg? url' const Example = () => ( <div> ...
  3. declare module '*.svg' { import { FC, SVGProps } from 'react' const content: FC<SVGProps<SVGElement>> export default content. }

What does responsive mean SVG? ›

SVG's exported from Illustrator CC are 'responsive' by default, in other words there is no height or width attributes, no dimensions. This can be great, but sometimes you may want to force dimensions. Say for example you want to use an SVG for a logo on your website, but you want it to be a set size.

How to make SVG path responsive? ›

10 golden rules for responsive SVGs
  1. Set up your tools correctly. ...
  2. Remove height and width attributes. ...
  3. Optimise and minify SVG output. ...
  4. Modify code for IE. ...
  5. Consider SVG for hero text. ...
  6. Leave width and height in place for progressive icons. ...
  7. Use vector-effects to keep hairlines thin. ...
  8. Remember bitmaps.
Mar 22, 2021

How to resize SVG image in React JS? ›

You can change the size using CSS transform: scale(2) in <ComponentName /> , which in React can be achieved using className or a global CSS file. Note: To change the color you can use . componentClass path { fill: "color" } , but if you change the scale on .

How to use animated icons in React? ›

react-icons-animated
  1. Get Started. Follow these simple steps: Install the npm package. ...
  2. Props. Icons components can implement an "isClosed" prop that is controlled by a parent component. ...
  3. Licence. The MIT License (MIT) ...
  4. Contributions. I'm currently looking for contributors to help out with this project.

Can SVG format be animated? ›

SVG supports the ability to change vector graphics over time, to create animated effects. SVG content can be animated in the following ways: Using SVG's animation elements [svg-animation].

How to install Lottie in React? ›

Installation
  1. Make sure you have the peer-dependencies installed: react and react-dom . Note: This library is using React Hooks so the minimum version required for both react and react-dom is v16. 8.0.
  2. Install lottie-react using yarn. yarn add lottie-react. or npm. npm i lottie-react.
Feb 19, 2023

How do I export an animated SVG? ›

Exporting artwork in SVG format
  1. In Animate, scrub or move the playhead to the appropriate frame.
  2. Select File > Export > Export Image. or select File > Publish Settings (select the SVG Image option in the Other Formats section.)
  3. Enter or browse to the location where you want to save the SVG file. ...
  4. Click Ok.
May 24, 2023

Top Articles
Latest Posts
Article information

Author: Maia Crooks Jr

Last Updated:

Views: 5827

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Maia Crooks Jr

Birthday: 1997-09-21

Address: 93119 Joseph Street, Peggyfurt, NC 11582

Phone: +2983088926881

Job: Principal Design Liaison

Hobby: Web surfing, Skiing, role-playing games, Sketching, Polo, Sewing, Genealogy

Introduction: My name is Maia Crooks Jr, I am a homely, joyous, shiny, successful, hilarious, thoughtful, joyous person who loves writing and wants to share my knowledge and understanding with you.