SVG morphing in React JS

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 (
         
            
         
      );
   }
}

class CheckBox extends React.Component {
   render() {
      return (
         
            
         
      );
   }
}

export default class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         checked: false,
      };
   }
   toggleChecked() {
      this.setState({ checked: !this.state.checked });
   }
   render() {
      return (
         
            {this.state.checked ? ( ) : (             )}            
); } }

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 −

Updated on: 2021-09-29T09:15:07+05:30

909 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements