1

I use react-intersection-observer and enter code here. I have multiple titles on my page and when I scroll, I want the animation to launch when the title is in the view.

This part ok, I get to trigger animation when visible.

Problem: I trigger animation after a delay of 300ms. The title is visible before the animation is triggered. I would like the text of my h2 to be hidden and then, when on view trigger animation.

How to achieve this ?

Here is my code :

import {InView} from "react-intersection-observer";

 <InView triggerOnce>
       {({ref, inView}) => (
           <h2
              ref={ref}
              className={`${
                 inView ? "delayed fade-in-right-animation" : null
              } mb-4 flex text-2xl font-bold`}>
             My title
            </h2>
        )}
</InView>
// css

.fade-in-right-animation {
        animation: fadeInRight 0.3s ease-in-out;
    }

    .delayed {
        animation-delay: 0.2s;
    }

    @keyframes fadeInRight {
        from {
            opacity: 0;
            transform: translateX(-100px);
        }
        to {
            opacity: 1;
        }
    }
Johan
  • 2,088
  • 2
  • 9
  • 37

1 Answers1

0

You could use conditional rendering with the inview value to show the H2 or not. Like below.

import {InView} from "react-intersection-observer";

 <InView triggerOnce>
       {({ref, inView}) => {
           return (
            <>
            {
               inview 
                  ? <h2
                    ref={ref}
                    className={`${
                     inView ? "delayed fade-in-right-animation" : null
                    } mb-4 flex text-2xl font-bold`}>
                      My title
                    </h2>
                  : <></>
            }
            </>
           )
         
       }}
</InView>
  • I tried this, the prblem is that now the h2 has no height. So the block under comes to its place when no h2 . It makes all the page move. Kind of glitchy – Johan Feb 28 '23 at 16:23
  • You could add some styling to the <> or div you're rendering instead of the H2 that has the same height? – Boudewijn Danser Feb 28 '23 at 18:44