DEV Community

Cover image for React Spring | Animation
Shubham-Tiwari-Anywhere
Shubham-Tiwari-Anywhere

Posted on

React Spring | Animation

Greetings to all front-end programmers. Today, I'll demonstrate how to use React Spring to build a basic fade-in animation effect.

Let's get started...

"use client"
import React, { useState } from 'react';
import { useSpring, animated } from '@react-spring/web';

/**
 * FadeInOutText is a React component that renders a div containing a
 * fading text effect. The text is initially invisible and can be toggled
 * between visible and invisible states by clicking a button.
 */
const FadeInOutText = () => {
  // isVisible keeps track of the visibility state of the text
  const [isVisible, setIsVisible] = useState(false);

  // fadeInOut is a spring animation that defines the opacity of the text
  const fadeInOut = useSpring({
    opacity: isVisible ? 1 : 0, // opacity is 1 when text is visible, 0 when invisible
  });

  /**
   * handleClick toggles the visibility state of the text.
   */
  const handleClick = () => {
    setIsVisible(!isVisible);
  };

  return (
    <div className='grid place-items-center'>
      {/* Button to toggle text visibility */}
      <button onClick={handleClick}>Toggle Text</button>
      {/* Animated div that applies the fadeInOut animation */}
      <animated.div style={fadeInOut}>
        {/* Render the text if it is visible */}
        {isVisible && <p>This is a fading text effect.</p>}
      </animated.div>
    </div>
  );
};

export default FadeInOutText;
Enter fullscreen mode Exit fullscreen mode

Conclusion

This code defines a React component called FadeInOutText that displays a fading text effect. Initially, the text is invisible. Clicking a button toggles the text between visible and invisible states using a spring animation for the fade effect.

THANK YOU FOR CHECKING THIS POST

You can contact me on -

Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
Email - shubhmtiwri00@gmail.com

You can help me with some donation at the link below Thank you👇👇
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well

Top comments (0)