7 - Text Animation Component (Fade/Scroll)

Description

Create a React component that animates text with a fade-in and scroll effect.

Algorithm

  1. Initialize a state variable to store the text's opacity and y-position.

  2. Render the text with inline styles for opacity and position.

  3. Define functions to update the state variables for animation.

  4. Use the setTimeout function to animate the text.

Classes

TextAnimation: A React component that manages the text's animation state and renders the animated text.

Code

import React, { useState, useEffect } from 'react';

function TextAnimation() {
  const [opacity, setOpacity] = useState(0);
  const [yPosition, setYPosition] = useState(20);

  const animateText = () => {
    setOpacity((prevOpacity) => prevOpacity + 0.1);
    setYPosition((prevYPosition) => prevYPosition - 1);
  };

  useEffect(() => {
    const animationInterval = setInterval(animateText, 50);
    return () => clearInterval(animationInterval);
  }, []);

  return (
    <p
      style={{
        opacity,
        transform: `translateY(${yPosition}px)`,
        transition: 'opacity 0.5s, transform 0.5s',
      }}
    >
      Animated Text
    </p>
  );
}

export default TextAnimation;

Explanation

The code defines a TextAnimation component that utilizes the useState hook to initialize state variables for the text's opacity and y-position. The component renders the text with inline styles for opacity and position. The animateText function updates the state variables to animate the text. The useEffect hook is used to create an interval to call the animateText function every 50 milliseconds, creating the animation effect.

Possible Future Enhancements

  • Add more animation effects (e.g., scale, rotation).

  • Implement a props system to customize the animation.

  • Use a library like GSAP for more advanced animation control.

  • Integrate with a parent component to trigger the animation on mount/unmount.

Last updated