I'm just starting out with React and I want to trigger a CSS @keyframes animation when my element enters the viewport.
To achieve this, I am using the Intersection Observer with the help of the useOnScreen hook from
Here is my JSX :
import React, {useEffect, useRef, useState} from 'react'
import './landing.scss'
function useOnScreen(options){
const ref = React.useRef();
const [visible, setVisible] = React.useState(false);
React.useEffect(() => {
const observer = new IntersectionObserver(([entry]) => {
setVisible(entry.isIntersecting);
}, options);
if (ref.current) {
observer.observe(ref.current);
}
return () => {
if (ref.current) {
observer.unobserve(ref.current);
}
}
}, [ref, options])
return [ref, visible];
}
const Landing = () => {
const [ref, visible] = useOnScreen();
return(
<>
<div className="titleBox">
<h2 style={{ animationDuration: `0.5s`, animationIterationCount: 1, animationName: visible ? "showTopText" : ``, animationDelay: "0.3s", animationTimingFunction: "ease" }}>My text</h2>
</div>
</>
)
}
My scss :
@keyframes showTopText {
0% {top: 100%;}
100% {top: 0;}
}
.titleBox{
width: 100%;
height: 64px;
overflow: hidden;
position: relative;
h2{
font-size: 56px;
line-height: 64px;
width: 100%;
font-weight: normal;
position: absolute;
}
}
The challenge I am facing is that the animation repeats each time the element re-enters the screen, and also my text appears at top: 0%;
and disappears to top: 100%;
when the animation starts.
Any suggestions on how to solve this issue?