How to use the useInView hook for triggering animations on scroll in Next.js



Image not found!!

To trigger animations on scroll in Next.js using the useInView hook, you'll need to follow these steps:

  1. Install the necessary packages: Make sure you have the required packages installed. You'll need react-intersection-observer for the useInView hook and any animation library of your choice (e.g., framer-motion).

    bash
    npm install react-intersection-observer framer-motion
  2. Import the necessary modules in your component file:

    jsx
    import { useInView } from 'react-intersection-observer'; import { motion } from 'framer-motion';
  3. Define your animation:

    jsx
    const fadeInUp = { hidden: { opacity: 0, y: 20 }, visible: { opacity: 1, y: 0 }, };
  4. Use the useInView hook to trigger the animation when the component is in view:

    jsx
    const YourComponent = () => { const [ref, inView] = useInView({ triggerOnce: true, // Only trigger the animation once }); return ( <motion.div ref={ref} initial="hidden" animate={inView ? "visible" : "hidden"} variants={fadeInUp} > {/* Your component content goes here */} <h1>Your Animated Component</h1> </motion.div> ); }; export default YourComponent;

    In this example, the useInView hook returns a ref and a boolean value (inView). The ref should be applied to the component you want to animate. The inView boolean indicates whether the component is currently in the viewport. The motion.div component from framer-motion is used to apply the animation based on the inView value.

Remember to import and configure any additional styling or animations based on your specific requirements. This example uses a simple fade-in-up animation, but you can customize it according to your needs.