7 - Text Animation Component (Fade/Scroll)

Description

Develop a reusable React component that animates text elements using fade-in and scrolling effects. The component should:

  • Accept text content as a prop.

  • Allow customization of animation speed and type (fade-in or scrolling).

  • Trigger the animation automatically or on demand.

Algorithm

  1. State Management:

    • Use React's useState hook to manage animation states:

      • isVisible: Boolean to control text visibility.

      • scrollPosition: Number to track scrolling progress.

  2. Component Lifecycle:

    • Use useEffect to:

      • Start the animation automatically when the component mounts.

      • Update the scroll position on each render for smooth scrolling.

  3. Animation Logic:

    • Fade-in:

      • Use CSS transitions to gradually change the text's opacity from 0 to 1.

      • Conditionally apply a class to trigger the transition based on isVisible.

    • Scrolling:

      • Use JavaScript's requestAnimationFrame for smooth scrolling.

      • Increment scrollPosition within the animation loop.

      • Apply a translateY transformation to the text element based on scrollPosition.

  4. Customization:

    • Accept props for:

      • text: The text to animate.

      • animationSpeed: Duration of the animation.

      • animationType: 'fade-in' or 'scroll'.

      • trigger: 'auto' or 'manual'.

Code

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

function TextAnimation({ text, animationSpeed = 1000, animationType = 'fade-in', trigger = 'auto' }) {
  const [isVisible, setIsVisible] = useState(false);
  const [scrollPosition, setScrollPosition] = useState(0);

  useEffect(() => {
    if (trigger === 'auto') {
      startAnimation();
    }
  }, [trigger]);

  const startAnimation = () => {
    setIsVisible(true);

    if (animationType === 'scroll') {
      const animationFrame = requestAnimationFrame(() => {
        setScrollPosition((prevPosition) => prevPosition + 1);
        animationFrame; // Request the next frame for continuous scrolling
      });
    }
  };

  return (
    <div className={`text-animation ${animationType}`}>
      <p style={{ transform: `translateY(${scrollPosition}px)` }}>{text}</p>
    </div>
  );
}

export default TextAnimation;

Explanation

  • State Handling: Manages visibility and scroll position.

  • Animation Control: Uses useEffect for lifecycle management and requestAnimationFrame for smooth scrolling.

  • Customization: Accepts props for text, speed, type, and trigger.

  • CSS Classes: Apply appropriate classes for fade-in and scrolling animations.

Additional Notes

  • Multiple Animations: Consider using a library like Framer Motion for complex animations.

  • Accessibility: Ensure animations don't hinder user experience for those with disabilities.

  • Triggering Events: Allow animation start/stop on user events (e.g., hover, click).

Last updated