Giter VIP home page Giter VIP logo

thebuilder / react-intersection-observer Goto Github PK

View Code? Open in Web Editor NEW
4.8K 18.0 176.0 6.47 MB

React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport.

Home Page: https://react-intersection-observer.vercel.app

License: MIT License

JavaScript 3.00% TypeScript 95.65% HTML 0.98% MDX 0.37%
intersectionobserver-api react performance scrolling intersectionobserver monitor visibility viewport lazy-loading hooks

react-intersection-observer's Introduction

react-intersection-observer

Version Badge GZipped size Test License Downloads

React implementation of the Intersection Observer API to tell you when an element enters or leaves the viewport. Contains both a Hooks, render props and plain children implementation.

Features

  • πŸͺ Hooks or Component API - With useInView it's easier than ever to monitor elements
  • ⚑️ Optimized performance - Reuses Intersection Observer instances where possible
  • βš™οΈ Matches native API - Intuitive to use
  • πŸ›  Written in TypeScript - It'll fit right into your existing TypeScript project
  • πŸ§ͺ Ready to test - Mocks the Intersection Observer for easy testing with Jest or Vitest
  • 🌳 Tree-shakeable - Only include the parts you use
  • πŸ’₯ Tiny bundle - Around ~1.15kB for useInView and ~1.6kB for <InView>

Open in StackBlitz

Installation

Install the package with your package manager of choice:

npm install react-intersection-observer --save

Usage

useInView hook

// Use object destructuring, so you don't need to remember the exact order
const { ref, inView, entry } = useInView(options);

// Or array destructuring, making it easy to customize the field names
const [ref, inView, entry] = useInView(options);

The useInView hook makes it easy to monitor the inView state of your components. Call the useInView hook with the (optional) options you need. It will return an array containing a ref, the inView status and the current entry. Assign the ref to the DOM element you want to monitor, and the hook will report the status.

import React from "react";
import { useInView } from "react-intersection-observer";

const Component = () => {
  const { ref, inView, entry } = useInView({
    /* Optional options */
    threshold: 0,
  });

  return (
    <div ref={ref}>
      <h2>{`Header inside viewport ${inView}.`}</h2>
    </div>
  );
};

Render props

To use the <InView> component, you pass it a function. It will be called whenever the state changes, with the new value of inView. In addition to the inView prop, children also receive a ref that should be set on the containing DOM element. This is the element that the Intersection Observer will monitor.

If you need it, you can also access the IntersectionObserverEntry on entry, giving you access to all the details about the current intersection state.

import { InView } from "react-intersection-observer";

const Component = () => (
  <InView>
    {({ inView, ref, entry }) => (
      <div ref={ref}>
        <h2>{`Header inside viewport ${inView}.`}</h2>
      </div>
    )}
  </InView>
);

export default Component;

Plain children

You can pass any element to the <InView />, and it will handle creating the wrapping DOM element. Add a handler to the onChange method, and control the state in your own component. Any extra props you add to <InView> will be passed to the HTML element, allowing you set the className, style, etc.

import { InView } from "react-intersection-observer";

const Component = () => (
  <InView as="div" onChange={(inView, entry) => console.log("Inview:", inView)}>
    <h2>Plain children are always rendered. Use onChange to monitor state.</h2>
  </InView>
);

export default Component;

Note
When rendering a plain child, make sure you keep your HTML output semantic. Change the as to match the context, and add a className to style the <InView />. The component does not support Ref Forwarding, so if you need a ref to the HTML element, use the Render Props version instead.

API

Options

Provide these as the options argument in the useInView hook or as props on the <InView /> component.

Name Type Default Description
root Element document The Intersection Observer interface's read-only root property identifies the Element or Document whose bounds are treated as the bounding box of the viewport for the element which is the observer's target. If the root is null, then the bounds of the actual document viewport are used.
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). Also supports percentages, to check if an element intersects with the center of the viewport for example "-50% 0% -50% 0%".
threshold number or number[] 0 Number between 0 and 1 indicating the percentage that should be visible before triggering. Can also be an array of numbers, to create multiple trigger points.
onChange (inView, entry) => void undefined Call this function whenever the in view state changes. It will receive the inView boolean, alongside the current IntersectionObserverEntry.
trackVisibility πŸ§ͺ boolean false A boolean indicating whether this Intersection Observer will track visibility changes on the target.
delay πŸ§ͺ number undefined A number indicating the minimum delay in milliseconds between notifications from this observer for a given target. This must be set to at least 100 if trackVisibility is true.
skip boolean false Skip creating the IntersectionObserver. You can use this to enable and disable the observer as needed. If skip is set while inView, the current state will still be kept.
triggerOnce boolean false Only trigger the observer once.
initialInView boolean false Set the initial value of the inView boolean. This can be used if you expect the element to be in the viewport to start with, and you want to trigger something when it leaves.
fallbackInView boolean undefined If the IntersectionObserver API isn't available in the client, the default behavior is to throw an Error. You can set a specific fallback behavior, and the inView value will be set to this instead of failing. To set a global default, you can set it with the defaultFallbackInView()

InView Props

The <InView /> component also accepts the following props:

Name Type Default Description
as IntrinsicElement 'div' Render the wrapping element as this element. Defaults to div. If you want to use a custom component, please use the useInView hook or a render prop instead to manage the reference explictly.
children ({ref, inView, entry}) => ReactNode or ReactNode undefined Children expects a function that receives an object containing the inView boolean and a ref that should be assigned to the element root. Alternatively pass a plain child, to have the <InView /> deal with the wrapping element. You will also get the IntersectionObserverEntry as entry, giving you more details.

Intersection Observer v2 πŸ§ͺ

The new v2 implementation of IntersectionObserver extends the original API, so you can track if the element is covered by another element or has filters applied to it. Useful for blocking clickjacking attempts or tracking ad exposure.

To use it, you'll need to add the new trackVisibility and delay options. When you get the entry back, you can then monitor if isVisible is true.

const TrackVisible = () => {
  const { ref, entry } = useInView({ trackVisibility: true, delay: 100 });
  return <div ref={ref}>{entry?.isVisible}</div>;
};

This is still a very new addition, so check caniuse for current browser support. If trackVisibility has been set, and the current browser doesn't support it, a fallback has been added to always report isVisible as true.

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.

Recipes

The IntersectionObserver itself is just a simple but powerful tool. Here's a few ideas for how you can use it.

FAQ

How can I assign multiple refs to a component?

You can wrap multiple ref assignments in a single useCallback:

import React, { useRef, useCallback } from "react";
import { useInView } from "react-intersection-observer";

function Component(props) {
  const ref = useRef();
  const { ref: inViewRef, inView } = useInView();

  // Use `useCallback` so we don't recreate the function on each render
  const setRefs = useCallback(
    (node) => {
      // Ref's from useRef needs to have the node assigned to `current`
      ref.current = node;
      // Callback refs, like the one from `useInView`, is a function that takes the node as an argument
      inViewRef(node);
    },
    [inViewRef],
  );

  return <div ref={setRefs}>Shared ref is visible: {inView}</div>;
}

rootMargin isn't working as expected

When using rootMargin, the margin gets added to the current root - If your application is running inside a <iframe>, or you have defined a custom root this will not be the current viewport.

You can read more about this on these links:

Testing

In order to write meaningful tests, the IntersectionObserver needs to be mocked. You can use the included react-intersection-observer/test-utils to help with this. It mocks the IntersectionObserver, and includes a few methods to assist with faking the inView state. When setting the isIntersecting value you can pass either a boolean value or a threshold between 0 and 1. It will emulate the real IntersectionObserver, allowing you to validate that your components are behaving as expected.

Method Description
mockAllIsIntersecting(isIntersecting) Set isIntersecting on all current Intersection Observer instances. The value of isIntersecting should be either a boolean or a threshold between 0 and 1.
mockIsIntersecting(element, isIntersecting) Set isIntersecting for the Intersection Observer of a specific element. The value of isIntersecting should be either a boolean or a threshold between 0 and 1.
intersectionMockInstance(element) Call the intersectionMockInstance method with an element, to get the (mocked) IntersectionObserver instance. You can use this to spy on the observe andunobserve methods.
setupIntersectionMocking(mockFn) Mock the IntersectionObserver, so we can interact with them in tests - Should be called in beforeEach. (Done automatically in Jest environment)
resetIntersectionMocking() Reset the mocks on IntersectionObserver - Should be called in afterEach. (Done automatically in Jest environment)

Testing Libraries

This library comes with built-in support for writing tests in both Jest and Vitest

Jest

Testing with Jest should work out of the box. Just import the react-intersection-observer/test-utils in your test files, and you can use the mocking methods.

Vitest

If you're running Vitest with globals, then it'll automatically mock the IntersectionObserver, just like running with Jest. Otherwise, you'll need to manually setup/reset the mocking in either the individual tests, or a setup file.

import { vi, beforeEach, afterEach } from "vitest";
import {
  setupIntersectionMocking,
  resetIntersectionMocking,
} from "react-intersection-observer/test-utils";

beforeEach(() => {
  setupIntersectionMocking(vi.fn);
});

afterEach(() => {
  resetIntersectionMocking();
});

You only need to do this if the test environment does not support beforeEach globally, alongside either jest.fn or vi.fn.

Other Testing Libraries

See the instructions for Vitest. You should be able to use a similar setup/reset code, adapted to the testing library you are using. Failing that, copy the code from test-utils.ts, and make your own version.

Fallback Behavior

You can create a Jest setup file that leverages the unsupported fallback option. In this case, you can override the IntersectionObserver in test files were you actively import react-intersection-observer/test-utils.

test-setup.js

import { defaultFallbackInView } from "react-intersection-observer";

defaultFallbackInView(true); // or `false` - whichever consistent behavior makes the most sense for your use case.

Alternatively, you can mock the Intersection Observer in all tests with a global setup file. Add react-intersection-observer/test-utils to setupFilesAfterEnv in the Jest config, or setupFiles in Vitest.

module.exports = {
  setupFilesAfterEnv: ["react-intersection-observer/test-utils"],
};

Test Example

import React from "react";
import { screen, render } from "@testing-library/react";
import { useInView } from "react-intersection-observer";
import {
  mockAllIsIntersecting,
  mockIsIntersecting,
  intersectionMockInstance,
} from "react-intersection-observer/test-utils";

const HookComponent = ({ options }) => {
  const { ref, inView } = useInView(options);
  return (
    <div ref={ref} data-testid="wrapper">
      {inView.toString()}
    </div>
  );
};

test("should create a hook inView", () => {
  render(<HookComponent />);

  // This causes all (existing) IntersectionObservers to be set as intersecting
  mockAllIsIntersecting(true);
  screen.getByText("true");
});

test("should create a hook inView with threshold", () => {
  render(<HookComponent options={{ threshold: 0.3 }} />);

  mockAllIsIntersecting(0.1);
  screen.getByText("false");

  // Once the threshold has been passed, it will trigger inView.
  mockAllIsIntersecting(0.3);
  screen.getByText("true");
});

test("should mock intersecing on specific hook", () => {
  render(<HookComponent />);
  const wrapper = screen.getByTestId("wrapper");

  // Set the intersection state on the wrapper.
  mockIsIntersecting(wrapper, 0.5);
  screen.getByText("true");
});

test("should create a hook and call observe", () => {
  const { getByTestId } = render(<HookComponent />);
  const wrapper = getByTestId("wrapper");
  // Access the `IntersectionObserver` instance for the wrapper Element.
  const instance = intersectionMockInstance(wrapper);

  expect(instance.observe).toHaveBeenCalledWith(wrapper);
});

Intersection Observer

Intersection Observer is the API used to determine if an element is inside the viewport or not. Browser support is excellent - With Safari adding support in 12.1, all major browsers now support Intersection Observers natively. Add the polyfill, so it doesn't break on older versions of iOS and IE11.

Unsupported fallback

If the client doesn't have support for the IntersectionObserver, then the default behavior is to throw an error. This will crash the React application, unless you capture it with an Error Boundary.

If you prefer, you can set a fallback inView value to use if the IntersectionObserver doesn't exist. This will make react-intersection-observer fail gracefully, but you must ensure your application can correctly handle all your observers firing either true or false at the same time.

You can set the fallback globally:

import { defaultFallbackInView } from "react-intersection-observer";

defaultFallbackInView(true); // or 'false'

You can also define the fallback locally on useInView or <InView> as an option. This will override the global fallback value.

import React from "react";
import { useInView } from "react-intersection-observer";

const Component = () => {
  const { ref, inView, entry } = useInView({
    fallbackInView: true,
  });

  return (
    <div ref={ref}>
      <h2>{`Header inside viewport ${inView}.`}</h2>
    </div>
  );
};

Polyfill

You can import the polyfill directly or use a service like polyfill.io to add it when needed.

yarn add intersection-observer

Then import it in your app:

import "intersection-observer";

If you are using Webpack (or similar) you could use dynamic imports, to load the Polyfill only if needed. A basic implementation could look something like this:

/**
 * Do feature detection, to figure out which polyfills needs to be imported.
 **/
async function loadPolyfills() {
  if (typeof window.IntersectionObserver === "undefined") {
    await import("intersection-observer");
  }
}

Low level API

You can access the observe method, that react-intersection-observer uses internally to create and destroy IntersectionObserver instances. This allows you to handle more advanced use cases, where you need full control over when and how observers are created.

import { observe } from "react-intersection-observer";

const destroy = observe(element, callback, options);
Name Type Required Description
element Element true DOM element to observe
callback ObserverInstanceCallback true The callback function that Intersection Observer will call
options IntersectionObserverInit false The options for the Intersection Observer

The observe method returns an unobserve function, that you must call in order to destroy the observer again.

Warning
You most likely won't need this, but it can be useful if you need to handle IntersectionObservers outside React, or need full control over how instances are created.

react-intersection-observer's People

Contributors

adambulmer avatar bnjm avatar brantphoto avatar dawsontoth avatar dependabot[bot] avatar ebonstar avatar emzoumpo avatar etripier avatar felixmosh avatar forabi avatar greenkeeper[bot] avatar igghera avatar jeetiss avatar joepvl avatar johnrackles avatar jstcki avatar junquann avatar karer avatar kpman avatar kwakcena avatar kylemh avatar malbernaz avatar mparisot-mm avatar nickspaargaren avatar oliverjash avatar prettierci-commits avatar ryanoglesby08 avatar thebuilder avatar v-iktor avatar zutigrm 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-intersection-observer's Issues

Incorrect use of babelrc

react-intersection-observer is used as a dependency in react-scroll-percentage, I am getting below issue in running jest test cases
Couldn't find preset "./.babelrc.js" relative to directory "/node_modules/react-intersection-observer"

react-scroll-percentage has a babelrc in that, which might be causing issue while transpiling the react-intersection-observer. Below link has detailed explanation of this.

parcel-bundler/parcel#482

I am not clear if react-intersection-observer has to add babelrc in them or react-scroll-percentage has to remove its babelrc.

Note: I am facing this issue with Jest only, webpack build is running properly.

[Question] How would you handle conditional rendering with hooks?

First, I'd like to say thank you for such a great tool. Very useful.

I ran into a situation I wanted to run by you, and see if you have any suggestions.

This is specifically when using functional components with conditional rendering.

Consider the following scenario:

export default () => {
  const ref = useRef();
  const inView = useInView(ref);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(false);
  }, []);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return <div ref={ref}>in view - {inView ? 'yes' : 'no'}</div>
};

In the above example, ref.current won't exist for the initial render. When the effect is run in useInView, it will fail to attach the observer.

When the isLoading state changes, a re-render will happen. However, the useInView effect is only run if one of the options changes.

Even if we add ref.current to the dependency array in the effect, this doesn't help. The reason being, the dependencies are checked against at the time of render, whereas react refs get modified after rendering. See facebook/react#14387 (comment).

If we remove the list of dependencies entirely, we can see the ref.current has the proper reference in useEffect on the subsequent render. This is because the hook execution is deferred until after render (and thus the reference has been updated). However this results in an infinite render loop for this scenario. This may be the reason you added dependencies to useEffect to begin with.


I apologize for not coming forward with a potential solution, but this one stumped me. useLayoutEffect doesn't help us here either, because the inView state is set asynchronously.

One "workaround" is to always include the ref in the rendered component, i.e.

if (isLoading) {
  return <div>Loading...<div ref={ref}></div>;
}

return <div ref={ref}>in view - {inView ? 'yes' : 'no'}</div>

However, this is not ideal and comes with its own set of pitfalls/challenges.

It may also be worth noting that this is a non-issue when using render props, since the ref is guaranteed to exist when the observer is attached.

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.8.3 to 16.8.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected πŸ€–


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of storybook is breaking the build 🚨

There have been updates to the storybook monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the storybook group definition.

storybook is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v4.1.0

Storybook 4.1 with performance and compatibility improvements! Highlights include:

  • Core: Performance optimizations on separate manager preview split, improved cold start, restart & rebuild (#4834)
  • React: add support for all versions of react (#4808)
  • Addon-CSSResources: new adddon to dynamically add/remove css (#4622)
  • React: use babel presets/plugins based on CRA. (#4836)
  • React-native: Add ability to filter story list (#4806)
  • React: Add TypeScript support for react-scripts (#4824)

There are dozens more fixes, features, and tweaks in the 4.1 release. See changelogs for 4.1.0-* for details.

Commits

The new version differs by 441 commits.

There are 250 commits in total.

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this πŸ’ͺ.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


The push permission to the Git repository is required.

semantic-release cannot push the version tag to the branch master on remote Git repository.

Please refer to the authentication configuration documentation to configure the Git credentials on your CI environment.


Good luck with your project ✨

Your semantic-release bot πŸ“¦πŸš€

Could observe one element only once

Simple problem - as long you are tracking elements via INSTANCE_MAP.set(element, instance) - one element could be associated with one one instance.

If, but any reason, 2 different observers observe one element - only one would work - the top one.

An in-range update of npm-run-all is breaking the build 🚨

The devDependency npm-run-all was updated from 4.1.3 to 4.1.4.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

npm-run-all is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Commits

The new version differs by 3 commits.

  • a79fbac πŸ”– 4.1.4
  • d97929c remove test in version script temporary
  • 57d72eb πŸ”₯ remove ps-tree

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Proposal: disabled prop

I would like to propose a new prop disabled that disables the observation temporarily. This would be ideal for server-side rendering, where you don't want the server to render elements that are in view, since that should only happen client-side.

Component cannot be polyfilled to level of IntersectionObserver

I really like this component! I'm hoping to use it in a few projects, but unfortunately I can't until it supports the same browsers that the IntersectionObserver polyfill does. The issue is the use of WeakMap here: https://github.com/thebuilder/react-intersection-observer/blob/master/src/intersection.ts#L17.

WeakMap cannot be polyfilled on IE10, among other browsers, because IE10 doesn't allow HTML elements to be extended (a key requirement to support the loosely-held references).

I think you could use a regular Map and delete as needed. You could also just set window.WeakMap = window.WeakMap || Map and lose out on garbage collection (probably not the best idea, but it does support older browsers without compromising on performance).

I'd be happy to put up a PR for either change. Wondering what you think and if you'd be open to the idea.

Can't pass className props in TypeScript

TypeScript compiler reports an error message like

Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<ReactIntersectionObserver> & Readonly<{ childre
n?:...'.

process.env.NODE_ENV is undefined

Hi,

Another team using this package noticed that when using their build system they would get a runtime error saying process.env.NODE_ENV is undefined or something to that effect. It seems like this library requires that environment variable to be set? We mitigated this by replacing this manually at build time for a temporary workaround. Our team is using 6.1.1 and we haven't hit this issue, but they are using 6.4.1. Any ideas?

Thanks,
Dharsan

Observer state is always true when renderd by array

import Observer from 'react-intersection-observer'
const images = [image1, image2, ...image10];

images.map((i, index) => {
 return (
    <Observer>
      {inView => <img src={i} key={index} />}
    </Observer>
  );
};

These images states' are invisible at first. Then they are all visible at same time. So, can we use this package to lazyload images which rendered by array ?

Align render functions

The next major release will align the children and render method, so they both require a ref.
Right now it's confusing if why one is different, and it's hard to remember when using the lib.

It'll still support rendering a React.Node as the children when using the onChange method.

An in-range update of react-testing-library is breaking the build 🚨

The devDependency react-testing-library was updated from 5.6.0 to 5.6.1.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

react-testing-library is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

Release Notes for v5.6.1

5.6.1 (2019-02-11)

Bug Fixes

Commits

The new version differs by 1 commits.

  • 8436c7e fix(TS): typing of testHook (#292)

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Is wrapping element really required

I feel like that tag prop should be optional, i.e., not with a default value, really optional, for only the cases the user actually needs a wrapping element.

An in-range update of storybook is breaking the build 🚨

There have been updates to the storybook monorepo:

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the storybook group definition.

storybook is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v4.0.9

Bug Fixes

  • Core: Use correct cache directory path (#4792)
  • Addon-Info: fix docgen description display (#4685)
  • Addon-storyshots-puppeteer: fix peerDependencies (#4828)
Commits

The new version differs by 13 commits.

  • 378688e v4.0.9
  • 33a4355 4.0.9 changelog
  • 453740f Merge pull request #4792 from alex-fournier/fix-cache-directory
  • 8d3ec44 Update addon-info snapshots to fix broken build
  • ec5d38f Merge pull request #4685 from MihaChicken/addon-info/fix-docgen-description
  • c647bd8 Merge pull request #4825 from y-nk/docs/guide-vue
  • 086e4a9 Merge pull request #4780 from niku/patch-1
  • 4bd15a8 Merge pull request #4828 from bertho-zero/patch-1
  • 59e35b7 Merge pull request #4830 from aliceyoung9/patch-1
  • 3e3ff41 Docs: Fix internal deadlink
  • 970adba addon-storyshots-puppeteer: fix peerDependencies
  • c8898a1 Revise the sample in README for ReactNative
  • 3d052ce Revise the sample in README for ReactNative

See the full diff

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Allow consumers to choose whether to add polyfill

I would like to use this library but without the polyfill. For users who do not support Intersection Observers, I will simply not observe anything. I will probably do this using a higher order component, that wraps the component with Observer only if Intersection Observers are supported.

For consumers who do want to use the polyfill, it's easy enough for them to add it to the application themselves. Therefore I would like to propose we remove the polyfill as a dependency, to increase flexibility of the library.

Allow for full `IntersectionObserver` options to be passed in?

First, thanks for the component, this is great!

I wanted to ask if the full options of IntersectionObserver API could be passed in? Right now it looks like only { threshold } is passed in, so it's missing the other options, like root and rootMargin.

Was this a deliberate decision? If not, would you accept a PR adding in the other options?

Initial inView is always true

Hello, thanks for making this nice enhancer.

I'm using v0.2.12. inView is initially true until the component goes out in and out of the view once. You can see an example in the storybook, where on a small viewport, the logger shows inView as true even though the bar is way below.

image

index.d.ts file seems causing typescript errors

Hi,

I recently updated to v6.1.0 from v5.0.3 and noticed that the index.d.ts file seems to be incorrect which causes typescript build errors. When trying to use the default import it comes back as undefined. (import Observer from "react-intersection-observer")

Worked around it by doing:
import * as Observer from "react-intersection-observer"
import { IntersectionObserverProps } from "react-intersection-observer"

const WrappedObserver = (Observer as any) as React.ComponentClass < IntersectionObserverProps >;

Now typescript will allow us to use Observer as usual.

return(
< WrappedObserver />
);

Thanks!

Use ref callback in hooks

So it turns out the initial hooks implementation i made relied on the user passing the ref to the hook. However this turns out to be a problem, since the hook can't detect when the ref changes.
This results in issues like #162 - The ref had to be declared in the first render.

As suggested by Dan on Twitter, it seems like use a ref callback method is a better solution. The impact of this, is the the API of the useInView hooks needs to be changed into:

const [ref, inView, entry] = useInView(options)

This will break if you are currently using the useInView hook, but i think i actually prefer this. It also means you don't have to make a useRef(), just to create a useInView hook.

PlainChildren and Infinite Scroll Behavior

Hi,

Right now I'm using this package for infinite scroll. I have a list of items and place an observed div at the bottom and load more items when onChange is called and inView is true. When render is called, more items are added and I place the observed element at the bottom of the list again if there are more items to load.

I noticed that if I scroll down very quickly, onChange isn't called which stops the loading of more items until the user scrolls up and then back down.

I was thinking this behavior could be due to my implementation I described where technically the inView for that element hasn't really changed? Though because of a React rerender I would have expected it to be reevaluated.

If this isn't a bug, is there a way to get the current inView status? Or is there a better way for me to implement this?

Thanks,
Dharsan

Deprecations and render prop performance

Hi there. Thanks for creating this great library.

The v6 release deprecates traditional render methods. Unfortunately, we have a use case where we can't use render props due to performance concerns.

We have to render a list of items which is the triple whammy:

  • It's big with complex items
  • It re-renders frequently and has animations
  • It is interactive

We've benchmarked it to death, including using render props for another HOC we have, and it's just not possible without adverse effects on performance. It's already slow on underpowered devices, every little bit counts.

We use react-intersection-observer as a virtualized rendering solution because for this specific list it's much faster than react-virtualized (initialization time especially). Would you consider un-deprecating at least the "child as React.Node" method?

Thanks

Edge and mobile browser quirks

Currently using this component extensively across various code bases I work on - thanks for the work !

Do you think it would be useful for me to add some docs on how to get around some of the quirks mentioned here (to do with Edge and mobile browsers) - or at least provide a bit of a heads up to users wanting to use this component ? See:
https://www.quirksmode.org/blog/archives/2017/10/intersection_ob.html
(Eg. I can get it to work quite well with edge by just tinkering with rootMargin for instance)

I know its not specifically related to react-intersection-observer but more about Intersection Observer support in browsers as of xyz date

Happy to throw up PR if you think it would be worthwhile

Usage of `IntersectionObserverEntry.isIntersecting`

Hi there,

I was looking at the code for this library and noticed that it uses IntersectionObserverEntry.isIntersecting if available, otherwise falling back to intersectionRatio:

inView = intersection.isIntersecting

In my tests, IntersectionObserverEntry.isIntersecting produced different results to intersectionRatio > threshold. isIntersecting is true if the element intersects with the viewport regardless of the threshold. See this example, where my threshold is 0.5 but isIntersecting is true even when the intersectionRatio is smaller: http://jsbin.com/nuvodim/2/edit?js,console,output

Is the browser doing the right thing here? If so, is it safe to use isIntersecting?

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.8.1 to 16.8.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).
  • βœ… now/package.json: is ready
  • βœ… now: Deployment has completed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.7.0-alpha.2 to 16.7.0.
  • The devDependency react-dom was updated from 16.7.0-alpha.2 to 16.7.0.
  • The devDependency react-test-renderer was updated from 16.7.0-alpha.2 to 16.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

Release Notes for v16.7.0

React DOM

Scheduler (Experimental)

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Create "useInView" hook

This should be created in a new hook.js file, so it can be used without affecting component itself.

Detect if a component has reached the center of viewport

Hello. Is there a way to determine if a component has reached a specific boundary of the viewport, say the center, with this library? Perhaps like the possibility of setting 'boundary' as seen in the react-waypoint library? I'm asking here first although I have a feeling your react-scroll-percentage would be able to achieve this. Thanks!

Better examples/demo

While the storybook is nice, it's more useful when developing the module.

It should be replaced by a better looking static site, that also demonstrates common usecases, like lazy images and animation triggers.

Demo Link

The demo link in the Readme isn't working.

screen shot 2017-07-19 at 1 51 30 pm

An in-range update of @types/jest is breaking the build 🚨

The devDependency @types/jest was updated from 24.0.1 to 24.0.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/jest is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of @types/react is breaking the build 🚨

The devDependency @types/react was updated from 16.8.2 to 16.8.3.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

@types/react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • ❌ continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Version v6.2.0 make the build failed

I am using react-lazy-images that depends on this package, and targeting the latest build in their dependencies. But recently my build failed, showing this error. And i just check, you are just published new version. Here is the log that i get:

./node_modules/react-intersection-observer/dist/react-intersection-observer.esm.js
Module parse failed: Unexpected token (236:6)
You may need an appropriate loader to handle this file type.
|       rootId,
|       rootMargin,
|       ...props
|     } = this.props;
|     const {


npm ERR! code ELIFECYCLE
npm ERR! errno 1

fyi, i am using "react-scripts": "1.1.5"

TypeScript validation

The TypeScript definition file should be validated against TypeScript, and ideally also against the library.
I'm not using TypeScript myself, so not sure what the best approach to this would be.

@zeevl, @forabi or @Kovensky - would one of you care to look at this? πŸ‘

Published type definitions are broken (bad folder structure)

Your output is using a different folder structure than your input, so the published types are broken. InView.d.ts and useInView.d.ts should be co-located with the .js files instead of moved into the typings subfolder.

../node_modules/react-intersection-observer/dist/typings/InView.d.ts:2:43 - error TS2307: Cannot find module './typings/types'.

2 import { IntersectionObserverProps } from './typings/types';
                                            ~~~~~~~~~~~~~~~~~

../node_modules/react-intersection-observer/dist/typings/useInView.d.ts:1:51 - error TS2307: Cannot find module './typings/types'.

1 import { HookResponse, IntersectionOptions } from './typings/types';
                                                    ~~~~~~~~~~~~~~~~~

Small bug in the latest release description

It shows that you should use:

const Component = () => {
  const [ref, inView] = useInView(ref, {
    threshold: 0,
  })

  return (
    <div ref={ref}>
      ...
    </div>
  )
}

But you forgot to remove the ref parameter. useInView(ref, {

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.