Haris Papadakis
Haris Papadakis

Reputation: 89

Integrating a jQuery plugin into NextJS

I'm trying to integrate a six years old jQuery plug-in but I can't.

I tried to use findDOMNode module from react-dom, even then React Official Docs way to integrate a jQuery plug-in but none of them.

This is my plug-in --> https://www.jqueryscript.net/layout/Fancy-Responsive-jQuery-Diamond-Layout-Plugin-diamonds-js.html

I'm getting a couple of errors like

TypeError: jquery__WEBPACK_IMPORTED_MODULE_8___default(...)(...).Diamonds is not a function

ReferenceError: the window is not defined // I'm getting this error because library use the windows in the last line

I'm also showing you my snippet which I use to initialize the element.

componentDidMount() {
  //   $(".diamondswrap").diamonds({
  //     size : 200, // Size of diamonds in pixels. Both width and height. 
  //     gap : 5, // Pixels between each square.
  //     hideIncompleteRow : false, // Hide last row if there are not enough items to fill it completely.
  //     autoRedraw : true, // Auto redraw diamonds when it detects resizing.
  //     itemSelector : ".item" // the css selector to use to select diamonds-items.
  // });

  if(typeof window !== 'undefined') {
    window.Diamonds = require('../assets/js/jquery.diamonds.js');
  }
  new Diamonds.Diamonds();
  }

Thanks, and sorry for my English!

Upvotes: 4

Views: 13768

Answers (1)

hiddenuser.2524
hiddenuser.2524

Reputation: 4988

I created a small Github repo where you can take a look: https://github.com/tudorgergely/jquery-plugin-nextjs/

Here is the working demo: https://jquery-plugin-nextjs.now.sh/

Basically you need a couple of things, first use dynamic without ssr for the component rendering jquery-diamonds:

const DynamicJqueryDiamonds = dynamic(
    () => import('../components/JqueryDiamonds'),
    { loading: () => <p>...</p>, ssr: false }
);

Then inside that component load jquery/diamonds in componentDidMount/useEffect:

    useEffect(() => {
        window.jQuery = require('../public/jquery-latest.min');
        window.Diamonds = require('../public/jquery.diamonds.js');

        window.jQuery("#demo").diamonds({
            size : 100, // Size of diamonds in pixels. Both width and height.
            gap : 5, // Pixels between each square.
            hideIncompleteRow : false, // Hide last row if there are not enough items to fill it completely.
            autoRedraw : true, // Auto redraw diamonds when it detects resizing.
            itemSelector : `.${styles.item}` // the css selector to use to select diamonds-items.
        });
    }, []);

and last thing, don't forget to include your css inside pages/index.js:

e.g.:

export default function Index() {
    return (
        <div>
            <Head>
                <title>Test</title>
                <link href="/diamonds.css" rel="stylesheet" key="test"/>
            </Head>
            <DynamicJqueryDiamonds/>
        </div>
    );
}

Upvotes: 11

Related Questions