SVG morphing in React JS

React JSJavascript LibraryFront End Technology

SVG morphing is quite useful where you can morph SVG images with a beautiful animation which will look really great. It is a technique to give a transition between two SVG images when one SVG changes to another SVG.

First create a React project −

npx create-react-app tutorialpurpose

Go to the project directory −

cd tutorialpurpose

Example

Download and install the react-svg-morph package −

npm install react-svg-morph --save

This package will allow us to implement premade morphing animation to our SVGs.

Add the following lines of code in App.js

import React from "react";
import ReactDOM from "react-dom";
import { MorphReplace } from "react-svg-morph";

class Checked extends React.Component {
   render() {
      return (
         <svg width="24" fill="#00ea00" height="24" viewBox="0 0 24 24">
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41- 1.41z" />
         </svg>
      );
   }
}

class CheckBox extends React.Component {
   render() {
      return (
         <svg width="24" height="24" fill="#666666" viewBox="0 0 24 24">
            <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z" />
         </svg>
      );
   }
}

export default class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         checked: false,
      };
   }
   toggleChecked() {
      this.setState({ checked: !this.state.checked });
   }
   render() {
      return (
         <div onClick={this.toggleChecked.bind(this)}>
            <MorphReplace width={100} height={100}>{this.state.checked ? ( <Checked key="checked" /> ) : (
               <CheckBox key="checkbox" />)}
            </MorphReplace>
         </div>
      );
   }
}

Explanation

The code is pretty much self-explanatory.

  • We created two SVG classes.

  • Then we created a main class where we have a function to change the state to true or false.

  • Then we created a MorphReplace component inside which we added our two SVGs, which will change whenever we click on them.

Output

Now, let's check the output −

raja
Published on 29-Sep-2021 09:06:19
Advertisements