Search code examples
javascriptsvgreactjsvivus

ReactJS & Vivus SVG Animation


I'm new to reactJS and I'm trying to make my SVG's animated in React and I am having some issues.

I got vivus from https://www.npmjs.com/package/vivus

import React from "react";
import ReactDOM from "react-dom";
import Vivus from "vivus";

export default class MySkills extends React.Component {
constructor() {
    super();
    new Vivus('my-div', {duration: 200, file: 'link/to/my.svg'});
}

render() {
    return (
        <section id="MySkills" className="mySkills">
            <div className="wrapper">
                <div id="my-div"></div>
            </div>
        </section>
    );
}
}

And this trows me an error. I think that the issue is with constructor, but I am not sure where to put the vivus object?

Error message:

Uncaught Error: Vivus [constructor]: "element" parameter is not related to an existing ID


Solution

  • You have to initialize your Vivus object after the component has been mounted.

    export default class MySkills extends React.Component {
        constructor() {
            super();
    
        }
        componentDidMount(){
            new Vivus('my-div', {duration: 200, file: 'link/to/my.svg'});
        }    
        render() {
            return (
                <section id="MySkills" className="mySkills">
                    <div className="wrapper">
                        <div id="my-div"></div>
                    </div>
                </section>
            );
        }
    }