Giter Site home page Giter Site logo

wellyshen / react-cool-inview Goto Github PK

View Code? Open in Web Editor NEW
1.5K 4.0 41.0 4.69 MB

😎 πŸ–₯️ React hook to monitor an element enters or leaves the viewport (or another element).

Home Page: https://react-cool-inview.netlify.app

License: MIT License

TypeScript 78.69% JavaScript 6.06% Shell 0.34% HTML 7.73% SCSS 7.19%
react hook inview viewport visibility lazy-loading scrolling animations impressions intersection-observer

react-cool-inview's Introduction

REACT COOL INVIEW

A React hook / component API that monitors an element enters or leaves the viewport (or another element) with highly-performant way, using Intersection Observer. It's lightweight and super flexible, which can cover all the cases that you need, like lazy-loading images and videos, infinite scroll web app, triggering animations, tracking impressions, and more. Try it you will πŸ‘πŸ» it!

❀️ it? ⭐️ it on GitHub or Tweet about it.

build status coverage status npm version npm downloads npm downloads gzip size All Contributors PRs welcome Twitter URL

demo

⚑️ Try yourself: https://react-cool-inview.netlify.app

Features

Requirement

To use react-cool-inview, you must use [email protected] or greater which includes hooks.

Installation

This package is distributed via npm.

$ yarn add react-cool-inview
# or
$ npm install --save react-cool-inview

Usage

react-cool-inview has a flexible API design, it can cover simple to complex use cases for you. Here are some ideas for how you can use it.

⚠️ Most modern browsers support Intersection Observer natively. You can also add polyfill for full browser support.

Basic usage

To monitor an element enters or leaves the viewport by the inView state and useful sugar events.

import { useInView } from "react-cool-inview";

const App = () => {
  const { observe, unobserve, inView, scrollDirection, entry } = useInView({
    threshold: 0.25, // Default is 0
    onChange: ({ inView, scrollDirection, entry, observe, unobserve }) => {
      // Triggered whenever the target meets a threshold, e.g. [0.25, 0.5, ...]

      unobserve(); // To stop observing the current target element
      observe(); // To re-start observing the current target element
    },
    onEnter: ({ scrollDirection, entry, observe, unobserve }) => {
      // Triggered when the target enters the viewport
    },
    onLeave: ({ scrollDirection, entry, observe, unobserve }) => {
      // Triggered when the target leaves the viewport
    },
    // More useful options...
  });

  return <div ref={observe}>{inView ? "Hello, I am πŸ€—" : "Bye, I am 😴"}</div>;
};

πŸ’‘ You don't have to call unobserve when the component is unmounted, this hook will handle it for you.

Using as a Component

Changes HelloText when it enters the viewport. The options can be passed through the props.

import { InView } from "react-cool-inview";

const HelloText = ({ inView, observe }) => (
  <div ref={observe}>{inView ? "Hello, I am πŸ€—" : "Bye, I am 😴"}</div>
);

const App = () => (
  <InView unobserveOnEnter>
    <HelloText />
  </InView>
);

πŸ’‘ InView passes observe and other props to the HelloText.

Lazy-loading Images

It's super easy to build an image lazy-loading component with react-cool-inview to boost the performance of your web app.

import { useInView } from "react-cool-inview";

const LazyImage = ({ width, height, ...rest }) => {
  const { observe, inView } = useInView({
    // Stop observe when the target enters the viewport, so the "inView" only triggered once
    unobserveOnEnter: true,
    // For better UX, we can grow the root margin so the image will be loaded before it comes to the viewport
    rootMargin: "50px",
  });

  return (
    <div className="placeholder" style={{ width, height }} ref={observe}>
      {inView && <img {...rest} />}
    </div>
  );
};

πŸ’‘ Looking for a comprehensive image component? Try react-cool-img, it's my other component library.

Infinite Scroll

Infinite scroll is a popular design technique like Facebook and Twitter feed etc., new content being loaded as you scroll down a page. The basic concept as below.

import { useState } from "react";
import { useInView } from "react-cool-inview";
import axios from "axios";

const App = () => {
  const [todos, setTodos] = useState(["todo-1", "todo-2", "..."]);
  const { observe } = useInView({
    // For better UX, we can grow the root margin so the data will be loaded earlier
    rootMargin: "50px 0px",
    // When the last item comes to the viewport
    onEnter: ({ unobserve }) => {
      // Pause observe when loading data
      unobserve();
      // Load more data
      axios.get("/todos").then((res) => {
        setTodos([...todos, ...res.todos]);
      });
    },
  });

  return (
    <div>
      {todos.map((todo, idx) => (
        <div ref={idx === todos.length - 1 ? observe : null}>{todo}</div>
      ))}
    </div>
  );
};

πŸ’‘ Compare to pagination, infinite scroll provides a seamless experience for users and it’s easy to see the appeal. But when it comes to render a large lists, performance will be a problem. But don't worry, react-cool-virtual can help you out!

Trigger Animations

Another great use case is to trigger CSS animations once they are visible to the users.

import { useInView } from "react-cool-inview";

const App = () => {
  const { observe, inView } = useInView({
    // Stop observe when the target enters the viewport, so the "inView" only triggered once
    unobserveOnEnter: true,
    // Shrink the root margin, so the animation will be triggered once the target reach a fixed amount of visible
    rootMargin: "-100px 0px",
  });

  return (
    <div className="container" ref={observe}>
      <div className={inView ? "fade-in" : ""}>I'm a 🍟</div>
    </div>
  );
};

Track Impressions

react-cool-inview can also play as an impression tracker, helps you fire an analytic event when a user sees an element or advertisement.

import { useInView } from "react-cool-inview";

const App = () => {
  const { observe } = useInView({
    // For an element to be considered "seen", we'll say it must be 100% in the viewport
    threshold: 1,
    onEnter: ({ unobserve }) => {
      // Stop observe when the target enters the viewport, so the callback only triggered once
      unobserve();
      // Fire an analytic event to your tracking service
      someTrackingService.send("πŸ‹ is seen");
    },
  });

  return <div ref={observe}>I'm a πŸ‹</div>;
};

Scrolling Direction

react-cool-inview not only monitors an element enters or leaves the viewport but also tells you its scroll direction by the scrollDirection object. The object contains vertical (y-axios) and horizontal (x-axios) properties, they're calculated whenever the target element meets a threshold. If there's no enough condition for calculating, the value of the properties will be undefined. In addition, the value of the properties will sync with the scrolling direction of the viewport.

import { useInView } from "react-cool-inview";

const App = () => {
  const {
    observe,
    inView,
    // vertical will be "up" or "down", horizontal will be "left" or "right"
    scrollDirection: { vertical, horizontal },
  } = useInView({
    // Scroll direction is calculated whenever the target meets a threshold
    // more trigger points the calculation will be more instant and accurate
    threshold: [0.2, 0.4, 0.6, 0.8, 1],
    onChange: ({ scrollDirection }) => {
      // We can also access the scroll direction from the event object
      console.log("Scroll direction: ", scrollDirection.vertical);
    },
  });

  return (
    <div ref={observe}>
      <div>{inView ? "Hello, I am πŸ€—" : "Bye, I am 😴"}</div>
      <div>{`You're scrolling ${vertical === "up" ? "⬆️" : "⬇️"}`}</div>
    </div>
  );
};

If you jump to a section by the Element.scrollTop and encounter the wrong value of the scrollDirection. You can use updatePosition method to correct the behavior.

import { useEffect } from "react";
import { useInView } from "react-cool-inview";

const App = () => {
  const { observe, scrollDirection, updatePosition } = useInView({
    threshold: [0.2, 0.4, 0.6, 0.8, 1],
  });

  useEffect(() => {
    window.scrollTo(0, 500);
    updatePosition(); // Ensure the target element's position has been updated after the "window.scrollTo"
  }, []);

  return (
    <div ref={observe}>
      <div>{`You're scrolling ${
        scrollDirection.vertical === "up" ? "⬆️" : "⬇️"
      }`}</div>
    </div>
  );
};

Intersection Observer v2

The Intersection Observer v1 can perfectly tell you when an element is scrolled into the viewport, but it doesn't tell you whether the element is covered by something else on the page or whether the element has any visual effects applied to it (like transform, opacity, filter etc.) that can make it invisible. The main concern that has surfaced is how this kind of knowledge could be helpful in preventing clickjacking and UI redress attacks (read this article to learn more).

If you want to track the click-through rate (CTR) or impression of an element, which is actually visible to a user, Intersection Observer v2 can be the savior. Which introduces a new boolean field named isVisible. A true value guarantees that an element is visible on the page and has no visual effects applied on it. A false value is just the opposite. The characteristic of the isVisible is integrated with the inView state and related events (like onEnter, onLeave etc.) to provide a better DX for you.

When using the v2, there're somethings we need to know:

To use Intersection Observer v2, we must set the trackVisibility and delay options.

import { useInView } from "react-cool-inview";

const App = () => {
  // With Intersection Observer v2, the "inView" not only tells you the target
  // is intersecting with the root, but also guarantees it's visible on the page
  const { observe, inView } = useInView({
    // Track the actual visibility of the target
    trackVisibility: true,
    // Set a minimum delay between notifications, it must be set to 100 (ms) or greater
    // For performance perspective, use the largest tolerable value as much as possible
    delay: 100,
    onEnter: () => {
      // Triggered when the target is visible and enters the viewport
    },
    onLeave: () => {
      // Triggered when the target is visible and leaves the viewport
    },
  });

  return <div ref={observe}>{inView ? "Hello, I am πŸ€—" : "Bye, I am 😴"}</div>;
};

How to Share A ref?

You can share a ref as follows:

import { useRef } from "react";
import { useInView } from "react-cool-inview";

const App = () => {
  const ref = useRef();
  const { observe } = useInView();

  return (
    <div
      ref={(el) => {
        observe(el); // Set the target element for monitoring
        ref.current = el; // Share the element for other purposes
      }}
    />
  );
};

Working in TypeScript

This hook supports TypeScript, you can tell the hook what type of element you are going to observe through the generic type:

const App = () => {
  const { observe } = useInView<HTMLDivElement>();

  return <div ref={observe} />;
};

πŸ’‘ For more available types, please check it out.

API

const returnObj = useInView(options?: object);

Return object

It's returned with the following properties.

Key Type Default Description
observe function To set a target element for monitoring or re-start observing the current target element.
unobserve function To stop observing the current target element.
inView boolean The visible state of the target element. If it's true, the target element has become at least as visible as the threshold that was passed. If it's false, the target element is no longer as visible as the given threshold. Supports Intersection Observer v2.
scrollDirection object The scroll direction of the target element. Which contains vertical and horizontal properties. See scroll direction for more information.
entry object The IntersectionObserverEntry of the target element. Which may contain the isVisible property of the Intersection Observer v2, depends on the browser compatibility.
updatePosition function To update the current position of the target element for some cases.

Parameter

The options provides the following configurations and event callbacks for you.

Key Type Default Description
root HTMLElement window The element that is used as the viewport for checking visibility of the target. Must be the ancestor of the target. Defaults to the browser viewport if not specified or if null.
rootMargin string 0px Margin around the root. Can have values similar to the CSS margin property, e.g. "10px 20px 30px 40px" (top, right, bottom, left). The values can be percentages. This set of values serves to grow or shrink each side of the root element's bounding box before computing intersections.
threshold number | number[] 0 Indicates at what percentage of the target's visibility the observer's callback should be executed. If you only want to detect when visibility passes the 50% mark, you can use a value of 0.5. If you want the callback to run every time visibility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1].
trackVisibility boolean false Indicates whether the intersection observer will track changes in a target’s visibility. It's required when using Intersection Observer v2.
delay number Indicates the minimum delay in milliseconds between notifications from the intersection observer for a given target. It's required when using Intersection Observer v2.
unobserveOnEnter boolean false Stops observe once the target element intersects with the intersection observer's root. It's useful when you only want to trigger the hook once, e.g. scrolling to run animations.
onChange function It's invoked whenever the target element meets a threshold specified for the intersection observer. The callback receives an event object which the same with the return object of the hook.
onEnter function It's invoked when the target element enters the viewport. The callback receives an event object which the same with the return object of the hook except for inView. Supports Intersection Observer v2.
onLeave function It's invoked when the target element leaves the viewport. The callback receives an event object which the same with the return object of the hook except for inView. Supports Intersection Observer v2.

rootMargin Not Working As Expected?

If your web app is running in an <iframe> or you have a custom root, the viewport won't be the current document. Read the doc to understand how do root and root margin work.

Intersection Observer Polyfill

Intersection Observer has good support amongst browsers, but it's not universal. You'll need to polyfill browsers that don't support it. Polyfills is something you should do consciously at the application level. Therefore react-cool-inview doesn't include it.

You can use W3C's polyfill:

$ yarn add intersection-observer
# or
$ npm install --save intersection-observer

Then import it at your app's entry point:

import "intersection-observer";

Or use dynamic imports to only load the file when the polyfill is required:

(async () => {
  if (!("IntersectionObserver" in window))
    await import("intersection-observer");
})();

Polyfill.io is an alternative way to add the polyfill when needed.

Performance Issues

Be aware that the callback of the onChange event is executed on the main thread, it should operate as quickly as possible. If any time-consuming needs to be done, use requestIdleCallback or setTimeout.

onChange = (event) => requestIdleCallback(() => this.handleChange(event));

Articles / Blog Posts

πŸ’‘ If you have written any blog post or article about react-cool-inview, please open a PR to add it here.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Welly
Welly

πŸ’» πŸ“– 🚧
Nhan Nguyen
Nhan Nguyen

πŸ’»
Yann Pringault
Yann Pringault

πŸ›
gabalafou
gabalafou

πŸ“–
Victor
Victor

πŸ› πŸš‡
Max
Max

πŸ’»
SaidMarar
SaidMarar

πŸ’»

This project follows the all-contributors specification. Contributions of any kind welcome!

react-cool-inview's People

Contributors

allcontributors[bot] avatar dependabot-preview[bot] avatar dependabot[bot] avatar gabalafou avatar kerumen avatar max-sym avatar saidmarar avatar victorlacorte avatar wellyshen avatar xregitx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-cool-inview's Issues

SEO Question

Hello, as a new React Next.js learner, I have a question.
Today I got this amazing package for my react app, and put my comp between inView so it only shows posts images on scroll, which makes the posts so fast and cool.
My question is,
Are photos still indexable by Google? Google will find the pictures and posts? How it will effect the SEO generally?

Thanks

rootMargin not working until after the first time intersecting

Bug Report

Describe the Bug

The rootMargin is being ignore until after the first time the IntersectionObserver fires isIntersecting.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Provide custom rootMargin and custom ref
  2. Scroll down
  3. Observe the isIntersecting is false until the element is visible.
  4. Scroll down again
  5. Observe the isIntersecting is true at the expected rootMargin

CodeSandbox Link

https://codesandbox.io/s/react-cool-inviewissues495-0g4yk

Expected Behavior

Should respect the rootMargin on the initial scroll

Screenshots

image

Your Environment

  • Device: MacBook Pro
  • OS: macOS X
  • Browser: Chrome
  • Version: v1.2.2

Ref not updating when conditionally applied

Bug Report

Describe the Bug

A clear and concise description of what the bug is.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Conditionally apply the ref
  2. Scroll to bottom
  3. Observe no callbacks fired and no entry exists

CodeSandbox Link

https://codesandbox.io/s/react-cool-inviewissues493-yks98

Expected Behavior

I would expect the observer to fire callbacks

Screenshots

image

Your Environment

  • Device: MacBook Pro
  • OS: macOS X
  • Browser: Chrome
  • Version: 1.2.2

Additional Information

Seems to be an issue when ref is conditionally set.

{hasNextPage && <div ref={triggerRef}>Loading...</div>}
{items.map((item, i) => {
	  return i === items.length - 1 ? (
	    <div ref={lastItemRef} key={item.id}>
	      {item.id}
	    </div>
	  ) : (
	    <div key={item.id}>{item.id}</div>
	  );
})}

Request support for multiple refs

Description

It's very normal to observe more than one element. Tracking visibility or lazy loading doesn't stop at only one component. I think it would be great if the library supports multiple refs.

Possible solution

react-intersection-observer use useCallback method inside a component to set the current node ref using useRef from react. I am sure you already looked into it but if you make a workaround or a stable solution out of it that would be very helpful.

scrollDirection reports wrong direction

Great hook you've put together, been using it for a while and it works like a treat!

I've discovered what I think is a bug. On the project I'm working on right now I have a navigation that jumps to different sections on the homepage. I've noticed that if I jump to a section (via scrollTop) and then scroll upwards, when onEnter triggers scrollDirection.vertical is up, when it should be down.

If I test with onChange I see up on the first threshold and the following ones will be down as expected.

I'm just getting ready to launch this project so I'll revisit this thread with a test case as soon as I have the time if you can't reproduce on your own.

Thanks again!

README should include TypeScript examples

Bug Report

Describe the Bug

There are good examples in the README but it's tough to tell how to get this working in TypeScript. There is an example in the demo folder but this doesn't run immediately in CodeSandbox so it's a little challenging to find it from there.

Since most refs from the hook will be used on divs, it would be helpful to have documentation in the README about the generic you can pass to make this work. Otherwise, you'll end up getting:

Type 'RefObject<HTMLElement>' is not assignable to type 'string | ((instance: HTMLDivElement | null) => void) | RefObject<HTMLDivElement> | null | undefined'.
  Type 'RefObject<HTMLElement>' is not assignable to type 'RefObject<HTMLDivElement>'.
    Property 'align' is missing in type 'HTMLElement' but required in type 'HTMLDivElement'.  TS2322

How to Reproduce

Use useInView in TypeScript without providing a generic.

Custom Ref not checked before calling (un)observe

Bug Report

Describe the Bug

If passing a custom ref to the hook, the observe and unobserve functions aren't checking that it isn't null before treating it as an Element.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Conditionally apply the ref
  2. Change condition to false
  3. Scroll
  4. Observe error Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'.

CodeSandbox Link

https://codesandbox.io/s/react-cool-inviewissues494-cd5lo

Expected Behavior

I would expect no error

Screenshots

image

Your Environment

  • Device: MacBook Pro
  • OS: macOS X
  • Browser: Chrome
  • Version: v1.2.2

Additional Information

It looks like there is a missing safety check that the ref.current isn't null.

Observer not unmounted?

Hi there,
I cannot figure out why useEffect is trying to set state here after component is unmounted. Even wierder is the fact that this error fires only once.

image

Do you have any clue why this would be a case?

Cheers for the coolest hooks, btw πŸ‘

Infinite re-renders

Bug Report

Describe the Bug

When I use this hook in any component, it causes infinite re-renders. Am I doing something wrong?

CodeSandbox Link

You can see it here: CodeSandbox.

Thanks

ScrollDirection isn't displaying the proper direction

Bug Report

Describe the Bug

While scrolling down, the scrollDirection doesn't update to say 'down'. When the new page of items loads, it causes the scroll bar to jump and reports the scrollDirection of 'up' of which, I (the user) never scrolled up and can be misleading.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Setup infinite scroll
  2. Scroll down
  3. Observe no scrollDirection while scrolling down
  4. Observe scrollDirection of 'up' when the screen repaints with new items

CodeSandbox Link

https://codesandbox.io/s/react-cool-inviewissues499-kl2xg

Expected Behavior

I would expect while scrolling to show the direction I'm scrolling.
I would expect after a period of time not scrolling, to remove the scrollDirection.
I would expect when new items load/render, the scrollDirection won't report the jump up.

Screenshots

image

Then scrolling after new load:
image

Your Environment

  • Device: MacBook Pro
  • OS: macOS X
  • Browser: Chrome
  • Version: v2.0.1

Additional Information

Is there a way to trigger onLeave when begin to leave

I notice that OnEnter will trigger when the element starts to enter the viewport, but OnLeave triggers when the element fully leaves the viewport.
I think after the element leaves the viewport, trigger some function just not helping too much.
Is there any way to trigger onLeave when the beginning? maybe a prop or something will do.

Great Library, Thank you for your work.

Typescript typing wrong for observe

You need to change observe to accept an optional element

I get an error when using useInView and useDimensions when trying to compose the observe callback :

  const { observe:observeInView, inView } = useInView({...})

  const { observe:observeDimension, currentBreakpoint } = useDimensions({...})

  let combinedObserve = useCallback(el=>{
    observeInView(el);
    observeDimension(el);
  }, [observeInView, observeDimension])

ts error is Expected 0 arguments, but got 1.ts(2554)

This is because observe is defined as :

    observe: () => void;

it needs to look something like

    observe: (element?: HTMLElement) => void

rootMargin must have pixel or percentage unit, but the β€œTrigger Animations” example uses a rootMargin of "-100px 0" which throws an error.

Bug Report

Describe the Bug

In the README file the Trigger Animations example uses a value of "-100px 0" for rootMargin, but rootMargin requires absolute pixel or percent units, otherwise it throws the following error:

Failed to construct 'IntersectionObserver': rootMargin must be specified in pixels or percent.

How to Reproduce

Just follow the example set in the Trigger Animations section of the README.

CodeSandbox Link

https://codesandbox.io/s/react-cool-inview-example-forked-bcf57

Expected Behavior

0 shouldn’t require a unit.

Screenshots

Add screenshots to help explain your problem.
image

Your Environment

  • Device: MacBook
  • OS: macOS BigSur 11.1
  • Browser: Chrome
  • Version: 89.0.4389.90 (Official Build) (x86_64)

Infinite rerenders when using ref={(el) => observe(el)}

Bug Report

Describe the Bug

This hook continually rerenders components when using ref={(el) => observe(el)}. The problem does not exist when using ref={observe}.

I need to use ref={(el) => observe(el)} because I need to observe a specific element with both useInView and useDimensions, so in the end I'll have something like this:

ref={(el) => {
    observeInView(el);
    observeDimensions(el)
}}

I've started having this issue with react-cool-dimensions v2.x.x, and react-cool-inview v2.x.x. Previously, I simply shared the same ref between both hooks, and everything was much easier to handle.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Go to https://codesandbox.io/s/loving-wave-zlokm?file=/src/App.js
  2. Click on Console on the browser preview
  3. Observe "Rendering..." being printed continuously...

Expected Behavior

It should render only when Γ¬nView` changes.

Your Environment

  • Device: Desktop PC
  • OS: Windows 10
  • Browser: Firefox v89
  • Version: v2.0.3

Is this preact friendly?

Hi, can we use cool-inview with preact? I have tried preact/compat but had some major issues like non-stop rerendering with the components.

inView is reporting incorrect value after loading more items until scroll.

Bug Report

Describe the Bug

The inView is still tracking the status of the initial last item after loading additional items.

How to Reproduce

Steps to reproduce the behavior, please provide code snippets or a repository:

  1. Setup infinite scrolling example
  2. Scroll down
  3. Observe inView remains true even after loading new items and settings new item with observe
  4. Observe the inView variable switches to false once the previously tracked item is fully off screen

CodeSandbox Link

https://codesandbox.io/s/react-cool-inviewissues500-qsn5q

Expected Behavior

I would expect after loading new items, and a new ref/observe being applied, that the previously tracked item, is no longer tracked and inView to report false.

Screenshots

image

Turns false after the initial last item (20 in the example) is off screen:
image

Your Environment

  • Device: MacBook Pro
  • OS: macOS X
  • Browser: Chrome
  • Version: v2.0.1

Additional Information

On an infinite scroll style example, I don't believe the observe is necessary within onEnter since the ref is calling the observe

Using cool inview only for src in a component

Hello, how can I use {inView && ... } inside a component? for example I want my Image just to be loaded in view, but it loads blurDataURL even before scrolling.

export default function Image({ src, ...rest }) {
  const { observe, inView } = useInView({
    onEnter: ({ unobserve }) => unobserve(), // only run once
  })
  return (
    <div ref={observe} className="max-w-screen-sm mx-auto text-center">
      <NextImage
        placeholder="blur"
        blurDataURL={`/_next/image?url=${src}&w=16&q=1`}
        src={`/_next/image?url=${src}&w=640&q=75`}
        {...rest}
      />
    </div>
  )
}

I was actually using inview for the whole component like this:

{inView &&   
<NextImage
    placeholder="blur"
    blurDataURL={`/_next/image?url=${src}&w=16&q=1`}
    src={`/_next/image?url=${src}&w=640&q=75`}
    {...rest}
/>}

but then I found that my Table of Content will be useless, because once the user clicks on them, it takes them to the wrong text, because images are not still all loaded. so then I decided to only use inView (which I don't know how to) for src only.
what do you think?

Thanks

No InView component

With version 3.0.0:
import { InView } from 'react-cool-inview' results in:
Module '"react-cool-inview"' has no exported member 'InView'
I used yarn to install

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.