Home > Software engineering >  Using hover-effect in Next JS
Using hover-effect in Next JS

Time:03-06

I'm trying to use an npm package called hover-effect inside a functional component, but I'm constantly bumping into some issues. I have used similar packages in create-react-app before but I'm new to next.js. See below how the package should be used:

import React, { useEffect, useRef } from "react";
import HoverEffect from "hover-effect";

export default Card(){
  const container = useRef();
    useEffect(() => {
      console.log(container.current);

       new HoverEffect({
        parent: container.current,
         intensity: 0.3,
         image1: "https://picsum.photos/420/620",
        image2: "https://picsum.photos/420/620",
       displacementImage:
           "https://raw.githubusercontent.com/robin-dela/hover-effect/master/images/fluid.jpg",
      });
    }, [container]);

  return(
    <>
       <div
          className="outer-image"
          ref={container}
          id="imgContainer"
          style={{ height: 500, width: 400 }}
        >
        </div>
    </>
  )

First of all, I tried to import it like any other npm module, but I get the issue SyntaxError: Cannot use import statement outside a module I have tried to import the package dynamically using next/dynamic in this way:

const HoverEffect = dynamic(() => import('hover-effect')), {ssr: false});

But when I try to use 'new' syntax I get the error 'HoverEffect' is not a constructor. I even tried adding next js transpile module as next.config.js:

const withTM = require("next-transpile-modules")([
  "gsap",
  "hover-effect",
]);
module.exports = withTM();

Anyone aware of any solution would be a lifesaver

CodePudding user response:

I just tried to import it in my localhost. This solution is working fine

const withTM = require("next-transpile-modules")([
  "gsap",
  "hover-effect",
]);
module.exports = withTM();

You also need to make sure that your import is like this

import HoverEffect from "hover-effect";
  • Related