0

I want to implement the isotope-layout in next.js project. For that, I tried to do that with the following blog. https://stackoverflow.com/questions/25135261/react-js-and-isotope-js Also, here is the codesandbox link. https://codesandbox.io/s/react-isotope-typescript-i9x5v?file=/src/App.tsx:1152-1504 That works for React project.

But when I try in next.js project, I can see the following error. enter image description here

If anyone has a solution, please help me! Thanks.

xorozo
  • 540
  • 4
  • 18

3 Answers3

1

I got this working in Next.js using:

const loadIsotope = () => require('isotope-layout');

let Isotope;

const MyComponent = () => {
  useEffect(() => {
    // return if window doesn't exist (i.e. server side)
    if (typeof window === 'undefined') return;

    // load Isotope
    Isotope = loadIsotope();
  }, []
};

Full example:

const loadIsotope = () => require('isotope-layout');

let Isotope;

const MyComponent = () => {

  // Ref of isotope container
  const containerRef = useRef();

  // Ref to store the isotope object
  const isotopeRef = useRef();

  useEffect(() => {
    // return if window doesn't exist (i.e. server side)
    if (typeof window === 'undefined') return;

    // load Isotope
    Isotope = loadIsotope();

    // use Isotope
    isotopeRef.current = new Isotope(containerRef.current, {
      itemSelector: '.my-item',
      layoutMode: 'fitRows',
    });
  }, []

  // render the content
  return (
    <div ref={containerRef}>
      {items.map((item, index) => (
        <div key={index} className="my-item">
          // your content here
        </div>
      ))}
    </div>
  );
};
Alex
  • 1,051
  • 1
  • 12
  • 26
0

I too faced the same problem with Isotope and NextJS. At last I used https://github.com/ZitRos/react-xmasonry and got it worked. Store items in the state, Add your own filter buttons to update the state, and loop through the items inside XMasonary.

This demo page will give an idea

https://github.com/ZitRos/react-xmasonry/blob/master/docs/jsx/ContentChangesDemo.jsx

  • Instead of relying on links in your answer to provide the necessary information, you should include things such as key information and code examples in your actual answer. Links stand to change over time. – damonholden Feb 23 '23 at 15:29
0

I want to add a bit to alex's answer, so it works with typescript and next.js. I had some issues and had to make some changes.

When using next.js you may still have issues with window not being defined.

Using this line of code into a component, which is called from the main page should fix the issue.

const loadIsotope = () => require('isotope-layout');

If you're using typescript, then use this line below.

  const isotopeRef = React.useRef<any>(null);`
phpwebdev
  • 103
  • 1
  • 10