React – animate mount and unmount of a single component

React – Animate Mount and Unmount of a Single Component

React is a popular JavaScript library used for building user interfaces. One common requirement in web development is to animate the mount and unmount of a single component in React. In this blog post, we will explore different ways to achieve this animation effect.

Solution 1: React Transition Group

React Transition Group is a popular library that provides a set of components for managing animations. To animate the mount and unmount of a single component, we can use the CSSTransition component from React Transition Group.

First, let’s install React Transition Group using npm:

npm install react-transition-group

Next, import the necessary components and CSS styles:

import React from 'react';
import { CSSTransition } from 'react-transition-group';
import './styles.css';

Create a component that needs to be animated:

const AnimatedComponent = ({ show }) => {
  return (
    <CSSTransition
      in={show}
      timeout={300}
      classNames="fade"
      unmountOnExit
    >
      <div className="component">Hello, World!</div>
    </CSSTransition>
  );
};

In the above code, we pass the show prop to determine whether the component should be mounted or unmounted. The timeout prop specifies the duration of the animation in milliseconds. The classNames prop defines the CSS class name for the animation. The unmountOnExit prop ensures that the component is unmounted after the animation completes.

Finally, add CSS styles to create the desired animation effect:

.fade-enter {
  opacity: 0;
}

.fade-enter-active {
  opacity: 1;
  transition: opacity 300ms;
}

.fade-exit {
  opacity: 1;
}

.fade-exit-active {
  opacity: 0;
  transition: opacity 300ms;
}

Now, you can use the AnimatedComponent in your application and control its mount and unmount using the show prop.

Solution 2: React Spring

React Spring is another powerful animation library for React. It provides a declarative way to create animations using JavaScript instead of CSS.

To animate the mount and unmount of a single component using React Spring, follow these steps:

First, install React Spring using npm:

npm install react-spring

Next, import the necessary components and hooks:

import React from 'react';
import { useTransition, animated } from 'react-spring';

Create a component that needs to be animated:

const AnimatedComponent = ({ show }) => {
  const transitions = useTransition(show, null, {
    from: { opacity: 0 },
    enter: { opacity: 1 },
    leave: { opacity: 0 },
  });

  return transitions.map(({ item, key, props }) =>
    item ? (
      <animated.div key={key} style={props} className="component">
        Hello, World!
      </animated.div>
    ) : null
  );
};

In the above code, we use the useTransition hook to define the animation transitions. The from object specifies the initial state, the enter object defines the state during mounting, and the leave object defines the state during unmounting.

Finally, use the AnimatedComponent in your application and control its mount and unmount using the show prop.

That’s it! You have learned two different ways to animate the mount and unmount of a single component in React. Choose the solution that best fits your project requirements and start creating stunning animations!

HTML Output:
“`html
React – Animate Mount and Unmount of a Single Component

React is a popular JavaScript library used for building user interfaces. One common requirement in web development is to animate the mount and unmount of a single component in React. In this blog post, we will explore different ways to achieve this animation effect.

Solution 1: React Transition Group

React Transition Group is a popular library that provides a set of components for managing animations. To animate the mount and unmount of a single component, we can use the CSSTransition component from React Transition Group.

First, let’s install React Transition Group using npm:

npm install react-transition-group

Next, import the necessary components and CSS styles:

import React from 'react';
import { CSSTransition } from 'react-transition-group';
import './styles.css';

Create a component that needs to be animated:

const AnimatedComponent = ({ show }) => {
  return (
    
      Hello, World!
    
  );
};

In the above code, we pass the show prop to determine whether the component should be mounted or unmounted. The timeout prop specifies the duration of the animation in milliseconds. The classNames prop defines the CSS class name for the animation. The unmountOnExit prop ensures that the component is unmounted after the animation completes.

Finally, add CSS styles to create the desired animation effect:

<

pre>.fade-enter { opacity: 0; }

.fade-enter-active { opacity: 1; transition: opacity 300ms; } .fade-exit { opacity: 1; } .fade Share this:FacebookX Related Posts: Framer motion animates smoothly based on tailwind classes, but not when specifying values using animate Framer motion animates smoothly based on tailwind classes, but not when specifying values using animate If you’re using Framer motion... How to create Handwriting animation using Framer-Motion? How to Create Handwriting Animation using Framer-Motion? Handwriting animation can add a unique and engaging touch to your web projects.... Add a Tooltip to a Div Add a Tooltip to a Div Tooltips are a great way to provide additional information or context to elements on... React – Login screen flashes on Loading React – Login screen flashes on Loading If you have ever encountered a situation where your login screen briefly flashes...
Posted September 9, 2023 in React by J. Kolby Tags: React Comments Leave a Reply Cancel replyYour email address will not be published. Required fields are marked *Comment * Name * Email * Website Save my name, email, and website in this browser for the next time I comment.
JS Duck Privacy Policy © Copyright 2023
window.WPCOM_sharing_counts = {"https:\/\/js-duck.com\/react-animate-mount-and-unmount-of-a-single-component\/":2704}; var ce4wp_form_submit_data = {"siteUrl":"https:\/\/js-duck.com","url":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","nonce":"6705e4829a","listNonce":"336c58bad5","activatedNonce":"c7b3069fb8"}; ( function() { var skipLinkTarget = document.querySelector( 'main' ), sibling, skipLinkTargetID, skipLink; // Early exit if a skip-link target can't be located. if ( ! skipLinkTarget ) { return; } /* * Get the site wrapper. * The skip-link will be injected in the beginning of it. */ sibling = document.querySelector( '.wp-site-blocks' ); // Early exit if the root element was not found. if ( ! sibling ) { return; } // Get the skip-link target's ID, and generate one if it doesn't exist. skipLinkTargetID = skipLinkTarget.id; if ( ! skipLinkTargetID ) { skipLinkTargetID = 'wp--skip-link--target'; skipLinkTarget.id = skipLinkTargetID; } // Create the skip link. skipLink = document.createElement( 'a' ); skipLink.classList.add( 'skip-link', 'screen-reader-text' ); skipLink.href = '#' + skipLinkTargetID; skipLink.innerHTML = 'Skip to content'; // Inject the skip link. sibling.parentElement.insertBefore( skipLink, sibling ); }() ); var hcbVars = {"showCopyBtn":"1","copyBtnLabel":"Copy code to clipboard"}; _stq = window._stq || []; _stq.push([ "view", JSON.parse("{\"v\":\"ext\",\"blog\":\"223076394\",\"post\":\"2704\",\"tz\":\"0\",\"srv\":\"js-duck.com\",\"j\":\"1:14.5\"}") ]); _stq.push([ "clickTrackerInit", "223076394", "2704" ]); wp.i18n.setLocaleData( { 'text direction\u0004ltr': [ 'ltr' ] } ); var _wpUtilSettings = {"ajax":{"url":"\/wp-admin\/admin-ajax.php"}}; var dracula = {"homeUrl":"https:\/\/js-duck.com","ajaxUrl":"https:\/\/js-duck.com\/wp-admin\/admin-ajax.php","pluginUrl":"https:\/\/js-duck.com\/wp-content\/plugins\/dracula-dark-mode","settings":{"excludes":[""],"colorMode":"presets","preset":"dracula"},"isPro":"","upgradeUrl":"https:\/\/js-duck.com\/wp-admin\/admin.php?billing_cycle=annual&page=dracula-pricing","nonce":"4eacf3fe8e"}; var sharing_js_options = {"lang":"en","counts":"1","is_stats_active":"1"}; var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-facebook' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-facebook' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomfacebook', 'menubar=1,resizable=1,width=600,height=400' ); return false; } } ); } )(); var windowOpen; ( function () { function matches( el, sel ) { return !! ( el.matches && el.matches( sel ) || el.msMatchesSelector && el.msMatchesSelector( sel ) ); } document.body.addEventListener( 'click', function ( event ) { if ( ! event.target ) { return; } var el; if ( matches( event.target, 'a.share-x' ) ) { el = event.target; } else if ( event.target.parentNode && matches( event.target.parentNode, 'a.share-x' ) ) { el = event.target.parentNode; } if ( el ) { event.preventDefault(); // If there's another sharing window open, close it. if ( typeof windowOpen !== 'undefined' ) { windowOpen.close(); } windowOpen = window.open( el.getAttribute( 'href' ), 'wpcomx', 'menubar=1,resizable=1,width=600,height=350' ); return false; } } ); } )();