I am using animate.css
and react-on-screen
npm packages, react-on-screen
package is to use TrackVisibility
component so I can make a nice fade-in effect. But I only want the animation to be done once. But every time when I scroll back to the component and it reappears on the screen the animation is retaken, and it's not such a great UI.
What should I do?
CodePudding user response:
You can use the visible
prop of the TrackVisibility
component in conjunction with the useState
hook, to keep track of whether the component has been animated or not. Once the component has been animated, you can use the animated
prop to turn off the animation.
import { useState } from 'react';
import { TrackVisibility } from 'react-on-screen';
function MyComponent() {
const [animated, setAnimated] = useState(false);
return (
<TrackVisibility onVisible={() => setAnimated(true)}>
<div className={`my-component ${animated ? '' : 'animated fadeIn'}`}>
<!-- ... -->
</div>
</TrackVisibility>
);
}
In this example, the first time the MyComponent
comes into view, the animated
state variable is set to false, and the animation is applied. But when the MyComponent
is scrolled out of view and then scrolled back into view, the animated
state variable is already set to true, so the animation is not applied again.
It's also worth noting that if you want to make the animation only once you can use the once
prop of the TrackVisibility
component:
<TrackVisibility once>