Gatsby - IntersectionObserver is not defined

Asked
Active3 hr before
Viewed126 times

9 Answers

definedgatsby
90%

Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,I am trying to build my gatsby project but I am unable due to the IntersectionObserver not being recognised. I use the intersectionObserver inside an InView component: , Stack Overflow Public questions & answers

It is the fact that IntersectionObserver is a browser API and you should not use browser APIs during server side rendering. Instead you try to utilize them after components have mounted. To solve this initialize your observer in useEffect() instead of useRef() as you currently do.

...
const observer = useRef();

useEffect(() => {
   observer.current = new IntersectionObserver({
      ...
   });
}, []); // do this only once, on mount
...
load more v
88%

i have to use the intersection-observer polyfill in gatsby v2 and i dont know how to import it correctly. i am already using the a Provider in the gatsby-browser.js so i cannot use require here because otherwise webpack fails bundling because of mixed import / require.,suggested way to import the polyfill, Enterprise

import React from "react";
import { Provider } from "react-redux";
import createStore from "./src/store/createStore";

export const wrapRootElement = ({ element }) => {
  const store = createStore();
  const ConnectedRootElement = <Provider store={store}>{element}</Provider>;
  return ConnectedRootElement;
};
load more v
72%

w3c/IntersectionObserver: Cannot track intersection with an iframe's viewport,It's not added to the TypeScript lib.d.ts file yet, so you will also have to extend the IntersectionObserverEntry with the isVisible boolean.,mockAllIsIntersecting(isIntersecting:boolean | number) Set isIntersecting on all current IntersectionObserver instances.

yarn add react - intersection - observer
load more v
65%

component---src-pages-contact-js-34c976efa1482a119a50.js contains metadata that defines the necessary resources for a specific route. We’ll come back to this–promise!,Our static build process will create an optimized, responsive hero image as static HTML that looks something like:,We even generate 2x DPi images for beautiful images, regardless of the screen quality!

Pretag
 Pretag team - issue, fix, solve, resolve
75%

API that can be used to understand the visibility and position of DOM elements relative to a containing element or to the top-level viewport. The position is delivered asynchronously and is useful for understanding the visibility of elements and implementing pre-loading and deferred loading of DOM content., Browser testing done via ,Location detection provided by ipinfo.io.

Pretag
 Pretag team - issue, fix, solve, resolve
40%

As not all browsers today support IntersectionObserver, we need to add intersection-observer polyfill by adding the following code in gatsby-browser.js.,As we want to load the disqus only at the first time the target intersect the root, we will need to unobserve the target. After creating the intersection observer we will observe the target.,Before we go further with lazy loading of disqus comment with intersection observer, lets understand about it’s options.

.css - 1 chxjt6 {
      position: absolute;right: 22 px;top: 24 px;padding: 8 px 12 px 7 px;border - radius: 5 px;color: #6f7177;-webkit-transition:background 0.3s ease;transition:background 0.3s ease;}.css-1chxjt6:hover{background:rgba(255,255,255,0.07);}.css-1chxjt6[data-a11y= "true"]: focus::after {
      content: "";position: absolute;left: -2 % ;top: -2 % ;width: 104 % ;height: 104 % ;border: 2 px solid
      var (--theme - ui - colors - accent, #6166DC);border-radius:5px;background:rgba(255,255,255,0.01);}@media (max-width:45.9375em){.css-1chxjt6{display:none;}}Copy 1const options = {
            2 root: null, 3 rootMargin: "0% 0% 100% 0%", 4 threshold: 05
         }
load more v
22%

It returns the full IntersectionObserver's entry object.,This React Hook detects visibility of a component on the viewport using the IntersectionObserver API natively present in the browser.,I discovered this way of using IntersectionObserver via this post medium while playing to build a lazy-loaded collection of images.

1import { RefObject, useEffect, useState } from 'react'2
3interface Args extends IntersectionObserverInit {4  freezeOnceVisible?: boolean5}6
7function useIntersectionObserver(8  elementRef: RefObject<Element>,9  {10    threshold = 0,11    root = null,12    rootMargin = '0%',13    freezeOnceVisible = false,14  }: Args,15): IntersectionObserverEntry | undefined {16  const [entry, setEntry] = useState<IntersectionObserverEntry>()17
18  const frozen = entry?.isIntersecting && freezeOnceVisible19
20  const updateEntry = ([entry]: IntersectionObserverEntry[]): void => {21    setEntry(entry)22  }23
24  useEffect(() => {25    const node = elementRef?.current // DOM Ref26    const hasIOSupport = !!window.IntersectionObserver27
28    if (!hasIOSupport || frozen || !node) return29
30    const observerParams = { threshold, root, rootMargin }31    const observer = new IntersectionObserver(updateEntry, observerParams)32
33    observer.observe(node)34
35    return () => observer.disconnect()36
37    // eslint-disable-next-line react-hooks/exhaustive-deps38  }, [elementRef, threshold, root, rootMargin, frozen])39
40  return entry41}42
43export default useIntersectionObserver
load more v
60%

Also, note that if you specified the root option, the target must be a descendant of the root element.,This rectangle is, finally, mapped to the coordinate space of the target's document.,Deciding whether or not to perform tasks or animation processes based on whether or not the user will see the result.

let options = {
   root: document.querySelector('#scrollArea'),
   rootMargin: '0px',
   threshold: 1.0
}

let observer = new IntersectionObserver(callback, options);
load more v
48%

Since react-scoll-percentage uses Intersection Observer, which is a relatively new browser API, we also need a polyfill for browsers that doesn’t support it yet. First install it as a dependency. ,I didn’t make a browser extension, rather, I just put the mechanics into my own blog post template. Since I’m on Gatsby and React, it was not that hard. Here’s how to do it:,There's a percentage there. And it changes when you are scrolling. Kinda cool isn‘t it? Now you can tab away from this site and still have a sense of how far you have read. That surely makes your existence a tad more pleasant, doesn‘t it?

import React, {useEffect} from 'react'
import {useScrollPercentage} from 'react-scroll-percentage'
import Container from '../components/container'
import BlogPost from '../components/blog-post'
import SEO from '../components/seo'
import Layout from '../containers/layout'
import {toPlainText} from '../lib/helpers'

const BlogPost = ({post}) => {
  const {title, _rawExcerpt} = post
  const [ref, percentage] = useScrollPercentage()
  
  useEffect(() => {
    if (post) {
      const percent = Math.round(percentage * 100)
      document.title = `${percent}% ${post.title}`
    }
  }, [percentage])
  
  return (
    <Layout>
      {post && <SEO title={` ${title}` || 'Untitled'} description={toPlainText(_rawExcerpt || [])} />}

      <div ref={ref}>
        {post && <BlogPost {...post} />}
      </div>
    </Layout>
  )
}

export default BlogPost

load more v

Other "defined-gatsby" queries related to "Gatsby - IntersectionObserver is not defined"