Next.js: Intersection Observer is not defined because of SSR...

Created on 21 Dec 2019  路  2Comments  路  Source: vercel/next.js

I am working with NextJS to rebuild and build upon an app that's built using CRA.

I copied over a custom intersection observer hook from my CRA app to Next but I keep getting an intersection observer not defined error and I'm sure it's because of the SSR side to Next.

I've read a few ways around this with the standard typeof window check but there must be a better way.

Is there better way to use the browser apis in Next?

Most helpful comment

@danboyle8637 we were having issues too with react-intersection-observer and Next but this ended up working for us in a class component:

import { InView } from 'react-intersection-observer';
...

<InView triggerOnce>
  {({ inView, ref }) => (
    <div ref={ref} style={{ width: '100%' }}>
      {inView && (
        <p>In View!</p>
      )}
    </div>
  )}
</InView>

All 2 comments

If you see errors around this it generally means you're using the React lifecycle incorrectly. the intersectionobserver should be initialized in useEffect which would prevent it from being initialized too early (server-side etc).


Please follow the issue template.

https://github.com/zeit/next.js/issues/new/choose

https://github.com/zeit/next.js/issues/new?template=8.Question_about_next.md

# Question about Next.js

GitHub Issues are reserved for Bug reports and Feature requests. The best place to get your question answered is to post it on https://spectrum.chat/next-js.

@danboyle8637 we were having issues too with react-intersection-observer and Next but this ended up working for us in a class component:

import { InView } from 'react-intersection-observer';
...

<InView triggerOnce>
  {({ inView, ref }) => (
    <div ref={ref} style={{ width: '100%' }}>
      {inView && (
        <p>In View!</p>
      )}
    </div>
  )}
</InView>
Was this page helpful?
0 / 5 - 0 ratings

Related issues

olifante picture olifante  路  3Comments

rauchg picture rauchg  路  3Comments

havefive picture havefive  路  3Comments

flybayer picture flybayer  路  3Comments

formula349 picture formula349  路  3Comments