Giter Site home page Giter Site logo

roderickhsiao / react-in-viewport Goto Github PK

View Code? Open in Web Editor NEW
335.0 335.0 29.0 4.68 MB

Detect if React component is in viewport

Home Page: https://roderickhsiao.github.io/react-in-viewport

License: MIT License

JavaScript 13.28% Shell 6.82% HTML 0.53% CSS 20.41% TypeScript 58.96%
intersection-observer lazyload react viewport

react-in-viewport's Introduction

Hey πŸ‘‹

Hi, Roderick here. I'm a software architect based in San Francisco Bay Area.

Drop me a message if you want to discuss interesting web ideas, questions, or potentially fun project to work together :)

Open for tech talks invitations, project architecture consulting (web performance, large scale web app, team mentoring and more). Book your free discussion session with me at Calendly.

About

  • πŸ™β€β™‚οΈ He/Him/His
  • 🐢 Dog Dad
  • πŸ‘¨β€πŸ’» Frontend Engineer
  • πŸ‡ΉπŸ‡Ό πŸ‡ΊπŸ‡Έ
  • Website

react-in-viewport's People

Contributors

charlescatta avatar chrissantamaria avatar dependabot[bot] avatar greenkeeper[bot] avatar jamiees2 avatar lencse avatar lovishtater avatar matt-malone avatar nunoar avatar roderickhsiao avatar tinder-rhsiao avatar tinder-salinawu avatar tylertyssedal avatar vhuerta 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

react-in-viewport's Issues

How can I disconnect on enter?

There is an example with a manual usage of IntersectionObserver

const imageObserver = new IntersectionObserver((entries, imgObserver) => {
  entries.forEach((entry) => {
   if (entry.isIntersecting) { // important string
      const lazyImage = entry.target
      console.log("lazy loading ", lazyImage)
      lazyImage.src = lazyImage.dataset.src
      lazyImage.classList.remove("lzy_img");
      imgObserver.unobserve(lazyImage); // important string
    }
  })
});
const arr = document.querySelectorAll('img.lzy_img')
arr.forEach((v) => {
  imageObserver.observe(v);
})

In your library how can I make my component unobserve?

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

The devDependency react-storybook-addon-chapters was updated from 3.1.4 to 3.1.5.

🚨 View failing branch.

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

react-storybook-addon-chapters 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (Details).

Commits

The new version differs by 1 commits.

  • de168ea package and version updates

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 🌴

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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (Details).

Release Notes for v5.1.4

Bug Fixes

  • Core: Fix core-js 3 errors (#7051)
  • UI: Fix syntax highlighter plain text not visible (#7057)
  • Addon-actions: Add default options to action(s) (#6438)

Dependency Upgrades

  • RN: add missing core-js dependency (#7016)
  • chore: set react version to 16.8.3 to match react native (#7008)
Commits

The new version differs by 18 commits.

  • 6d3d4fa v5.1.4
  • 09dd188 5.1.4 changelog
  • d860e51 core-js 3 errors fix (#7051)
  • 248667e Merge pull request #7016 from ForbesLindesay/patch-2
  • 09936b7 chore: set react version to 15.8.3 to match react native (#7008)
  • 169e9e4 FIX syntax highlighter plain text not visible (#7057)
  • 8bad7be Fix for issue 5932, adding default options to action(s) (#6438)
  • 7f253f5 Fixes typo in Introduction doc (#7059)
  • d6944fa documentation: Add note to addon-backgrounds docs Readme. #6915 (#7026)
  • f6fe014 Makes header consistent with sb.js.org (#7019)
  • 6472a04 Fixing Grammar (#7007)
  • cd7b027 Fix grammar in index.md (#7001)
  • 6ded779 docs: Clarify how to get local example running (#6999)
  • f64cff0 specifying where to get withInfo (#7013)
  • 257328b specifying where to get withInfo

There are 18 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 🌴

Stop events for a brief moment

This could be a new feature altogether.

What I am looking for: I want to stop the intersection observer/callback from my component. I want to have programmatic start and stop with context/custom hook.
What currently happens: Currently on every scroll event intersection observer is triggered and is calling the callback function.

Here is one case:
Let's say we have layout of tabs and we are treating tab selection as a pointer to specific div element on page where we scroll to on click of tab.
On scroll of the page I can set tab's state but if I try to do programmatic scroll on page (i.e. on click of tab) it will trigger the intersection observer and in turn the callback.

To handle such situations we can introduce another local state and expose method that can update it (either true/false). Based on this new state we can decide whether to invoke the callback on intersection observer.

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

There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.5.5 to 7.6.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 babel7 group definition.

babel7 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (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 eslint-plugin-react is breaking the build 🚨

The devDependency eslint-plugin-react was updated from 7.18.0 to 7.18.1.

🚨 View failing branch.

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

eslint-plugin-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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (Details).

Commits

The new version differs by 9 commits.

  • 000d6b8 Update CHANGELOG and bump version
  • ffdf69a [Fix] jsx-indent: Does not check indents for JSXText
  • 182b045 [Docs] use markdown-magic to automatically sort all rules alphabetically
  • 45b9d32 [Docs] jsx-props-no-spreading: fix typo to use correct rule
  • f9aee94 [Fix] jsx-props-no-spreading: add support for namespaced jsx components
  • e69b113 [Fix] jsx-no-target-blank: allow rel to be an expression
  • fc6e406 [meta] fix changelog date
  • 50df78f [Fix] sort-comp: | isn’t a valid regex flag; u and s are
  • a7f6a8b [Tests] on node v13

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 🌴

onExitViewport?

I want to fire event when a component fully enters, and fully exits.
I can do fully enter event by adjusting threshold, but I can't use it together with fully exit event.
It would be really nice to have onExitViewport(or onFullyLeaveViewport), and even onFullyEnterViewport as well.

Latest breaks Internet Explorer 11

Using HOC option, I pulled latest v1.0.0-alpha.28 and tested on Internet Explorer 11 with the intersection-observer polyfill installed. Error thrown until I downgraded to v1.0.0-alpha.20 where things were working as expected.

Unfortunately, IE11 does not produce the most helpful errors, SCRIPT16389: Unspecified error is what I saw in the console.

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

There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.5.0 to 7.5.5.

🚨 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 babel7 group definition.

babel7 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (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 🌴

handleViewport `options` is required in Typescript

Hey guys,

i stumbled over the typings for options which is required because the type is only IntersectionObserverInit. Are you able to make this optional? I am not sure if one can simply add | undefined in the jsdoc, as I didn't used this way of generating types so far.
For now, I am using {} as any object in my code but it would be nice, if I can omit this param fully.

Thanks for your help

Missing typescript declaration file for module

Could not find a declaration file for module 'react-in-viewport'. '/Users/Projects/xyz/node_modules/react-in-viewport/dist/index.js' implicitly has an 'any' type.

Try npm install @types/react-in-viewport if it exists or add a new declaration (.d.ts) file containing declare module 'react-in-viewport';ts(7016)

I'm using typescript for my project and tsconfig.json got strict mode true.

Would you like me to make one in DefinitelyTyped? Or is it already done?

useInViewport for multiple elements

I have problem, i creating moving thumbnails for my carousel slider. When thumbnails container is it does not fit in Viewport and active thumb is outside i want move my active thumb to viewport. Now useInViewport returns "true" when whole thumbs container is in Viewport and "false" when some part of him is out. I want have value "true" or "false" for each individual thumb. It is possible when i using hook?

i added a ref to each thumb as below:

    _{lightboxThumbsVisible === true &&
            React.Children.map(children, (child, index) => {
              return (
                <div
                  ref={thumbRef}
                  key={index}
                  data-id={index}
                  className={classNames(styles.dot, {
                    [styles.active]: index === activedIndex,
                  })}
                  onClick={onNavigate}
                >
                  {images[index]}
                </div>
              );
            })}_

Thank you for Your anwser,
Greetings.

IE syntax issue

Hi! I'm trying to use this lib with Next.Js and testing it in IE (v11), but in the console i'm getting this a syntax error in this line:

const forwardedRefComponent = (0, _react.forwardRef)((props, ref) => _react.default.createElement(TargetComponent, _extends({}, props, {{forwardedRef: ref}));

Of course it doesn't work, and i'm guessing that can be because of this: any idea? :/ Thanks! :)

Add rootMargin &/or threshold?

Problem: Trigger box is sometimes too big or too small
Platform: Firefox on Win10
Manual tests:

  1. Class based: Triggers when 1px is matching or goes into viewport. Kinda expected behavior IMHO, but may be a problem in some scenarios.
  2. Function based link example: triggers when the space between the link & the "onEnterViewport and onLeaveViewport callback" line enters & leaves the viewport; visually too early IMHO.

This report is not really a 'bug report'/suggestion per se, but as a FYI-to-warning about expectations how this component, can cause incorrect behavior/data. Either way is fine for lazy-load (or even desirable), but bad for say trackers. Tracker-triggers will be inaccurate due to triggers of the Intersection Observer happening before the user actually sees the tracked item, thus may have a % of false-positives.

If you think the extra code complexity is worth more fine-grained accuracy (eg to improve trackers), then there are options.

How to pass down props to a functional component in typescript through the HOC?

I have a functional component Body which takes in props from its parent component Parent.
I am unable to pass down the props by using
const ViewportBlock = handleViewport(Body)
as my rendering fails as no props are passed.
If I do something like
const ViewportBlock = handleViewport(() => Body(props))
then I am unable to attach the ref needed and hence the Intersection api does not work.
Can you please guide me how to use this here?
I am new to React so any help will be appreciated.

An in-range update of eslint-plugin-import is breaking the build 🚨

The devDependency eslint-plugin-import was updated from 2.16.0 to 2.17.0.

🚨 View failing branch.

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

eslint-plugin-import 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (Details).

Commits

The new version differs by 61 commits.

  • 0499050 bump to v2.17.0
  • f479635 [webpack] v0.11.1
  • 8a4226d Merge pull request #1320 from bradzacher/export-ts-namespaces
  • 988e12b fix(export): Support typescript namespaces
  • 70c3679 [docs] make rule names consistent
  • 6ab25ea [Tests] skip a TS test in eslint < 4
  • 405900e [Tests] fix tests from #1319
  • 2098797 [fix] export: false positives for typescript type + value export
  • 70a59fe [fix] Fix overwriting of dynamic import() CallExpression
  • e4850df [ExportMap] fix condition for checking if block comment
  • 918567d [fix] namespace: add check for null ExportMap
  • 2d21c4c Merge pull request #1297 from echenley/ech/fix-isBuiltIn-local-aliases
  • 0ff1c83 [dev deps] lock typescript to ~, since it doesn’t follow semver
  • 40bf40a [*] [deps] update resolve
  • 28dd614 Merge pull request #1304 from bradennapier/feature/typescript-export-type

There are 61 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 🌴

An in-range update of eslint-plugin-flowtype is breaking the build 🚨

The devDependency eslint-plugin-flowtype was updated from 3.9.0 to 3.9.1.

🚨 View failing branch.

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

eslint-plugin-flowtype 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (Details).

Release Notes for v3.9.1

3.9.1 (2019-05-23)

Bug Fixes

Commits

The new version differs by 1 commits.

  • 712d840 fix: requireReadOnlyReactProps (#406)

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 🌴

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

There have been updates to the enzyme monorepo:

    • The devDependency enzyme was updated from 3.8.0 to 3.9.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 enzyme group definition.

enzyme 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (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 🌴

ReferenceError: IntersectionObserver is not defined when testing

Hello!
I have react-in-viewport set up and working in my project, however now that I've started writing tests, every component containing handleViewport is throwing the above error. I'm using React testing library and am just trying to run a simple test with the viewport component in the render method provided by React testing library.

For example, testing a functional component called NotificationTestingPage works fine when switching the last line to export default NotificationsPage but throws errors when using export default handleViewport(NotificationsPage). The test looks like this:

test('should render', async () => { // const ref = React.createRef() render( <Provider store={mockStore}> <NotificationsPage /> </Provider> ) })

And the errors thrown are the reference error shown above and a console error looking like this:
The above error occurred in the <handleViewport(NotificationsPage)> component: coming from this file:
node_modules/react-in-viewport/dist/lib/handleViewport.js:56:37)

I've tried multiple things I've found in your docs/stack overflow but nothing seems to work, again the component itself functions as expected, it's just the test that throws this. Let me know if you have any ideas or if I'm missing something. Thanks in advance!

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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (Details).

Release Notes for v5.3.14

Bug Fixes

  • Centered: remove typesVersions attribute (#9907)
  • Props: Fix typescript unspecified default value (#9873)
  • Core: Use telejson for websockets channel (#9867)
  • Storyshots: Fix support for jsx/tsx config files (#9834)
  • MDX: Fix custom classes getting stripped (#8897)
  • Typescript: Add downlevel dts for 3.5 (#9847)
Commits

The new version differs by 41 commits.

  • 91d9c0c v5.3.14
  • 01ab760 Update peer dependencies to 5.3.14
  • bb222fa Prettier changelog
  • 1ddadfd 5.3.14 changelog
  • 5d2c9bf Merge pull request #9907 from storybookjs/fix-ts-export-for-addon-centered
  • 0395223 Merge pull request #9873 from storybookjs/9827-ts-default-values
  • 7ab4626 Merge pull request #9867 from storybookjs/websocket-cyclic-support
  • 57dd1e0 Merge pull request #9834 from davidgoli/support-jsx-preview-files
  • dd47540 Merge pull request #8897 from fraincs/#8504
  • c25cb3f Merge pull request #9906 from SoloJiang/chore-supplement-rax
  • d28e4a3 Merge pull request #9874 from dmartinjs/patch-3
  • 1995d87 Merge pull request #9894 from davidenglishmusic/docs-configuration-file-typos
  • 654aeb9 Merge pull request #9885 from gaguirre/patch-3
  • 853c72a Merge pull request #9857 from pchr-srf/patch-4
  • c2e39d2 Merge pull request #9844 from tskarhed/patch-4

There are 41 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 🌴

type error with `useInViewport`

Receiving a type error for the ref value passed to the useInViewport hook.

For the following code:


const Section = () => {
    const ref = useRef<HTMLElement>(null);
    const { enterCount, leaveCount } = useInViewport(ref);
  
    return (
      <section ref={ref}>
        <div>
          <h1>Hello</h1>
          <p>{`Enter viewport: ${enterCount} times`}</p>
          <p>{`Leave viewport: ${leaveCount} times`}</p>
        </div>
      </section>
    );
  };

The following type error appears:

Argument of type 'RefObject<HTMLElement>' is not assignable to parameter of type 'MutableRefObject<HTMLElement>'.
  Types of property 'current' are incompatible.
    Type 'HTMLElement | null' is not assignable to type 'HTMLElement'.
      Type 'null' is not assignable to type 'HTMLElement'.ts(2345)

Noticed that there was recently an update to this, not sure if this is working out as intended. It looks like there are truthy checks for any references to this target, so setting the useInViewport function signature to the following β€” with target being target: React.MutableRefObject<HTMLElement | null> β€” might be an option here:

(target: React.MutableRefObject<HTMLElement | null>, options?: Options, config?: Config, props?: Props)

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

There have been updates to the emotion monorepo:

    • The devDependency @emotion/core was updated from 10.0.22 to 10.0.27.

🚨 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 emotion group definition.

emotion 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (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 🌴

Missing typings file

Hi this is a great component, but yet i had a problem when using this in a react typescript project.
When i try to import something from it i get the following error
Could not find a declaration file for module 'react-in-viewport'. '/Users/aeatakishiyev/Documents/GitHub/ui-client/node_modules/react-in-viewport/dist/index.js'
i surpassed it by using require statement, but it would be great if you add a declaration module for this library

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

There have been updates to the babel7 monorepo:

    • The devDependency @babel/cli was updated from 7.7.7 to 7.8.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 babel7 group definition.

babel7 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
  • ❌ ci/circleci: build: Your tests failed on CircleCI (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 🌴

Add documentation for useInViewport

I noticed that the useInViewport hook has been in this project for 2 years, but I haven't seen any documentation from it, also, I'm not sure how to use it.

Could you add some documentation or an example?

The use of useInViewport affects the scrolling behaviour

I notice that my page has a different scrolling behaviour when I use useInViewport: the scrolling stops once the component comes into view. I was expecting the hook to only report on components entering and leaving, but it seems that it also affects the scrolling itself (it breaks the fluency of the scrolling).

PS I tested this by only adding or removing the call to useInViewport(), without using the information returned by this hook.

New issue From the last version

Im still looking at it, the error is:
Uncaught Error: Objects are not valid as a React child (found: object with keys {$$typeof, type, key, ref, props, _owner, _store}). If you meant to render a collection of children, use an array instead.

we are on react 17.

I will for now force previous version

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.