Code Monkey home page Code Monkey logo

react-lazyloading's Introduction

REACT LAZY LOAD

Version License Size

React Lazy Loading - It is easy to integrate with React to Lazyload components, Images, etc. It will monitor element and tell you when element enters into the viewport. So that can perform any operation when the component in viewport and initial load will get reduce. Implementing "infinite scrolling" web sites, where more and more content is loaded and rendered as you scroll, so that the user doesn't have to flip through pages.
Internally used Intersection Observer API

๐Ÿ’ฅ๐Ÿ’ฅ๐Ÿ’ฅ React library for Multiselect Dropdown. Check it Out ๐Ÿ’ฅ๐Ÿ’ฅ๐Ÿ’ฅ

Features

  • ๐ŸŽง Hooks or Component - With useVisibilityHook it's easier to monitor elements and perform any operations.
  • ๐Ÿ”ฅ Performance - No multiple listener for scroll, resize, etc.
  • ๐Ÿ”ฆ Bundle - Light weight, ~3.5kb
  • ๐ŸŽ Features - forceVisible, forceCheck to manually perform operations.
  • ๐Ÿ’ฅ Memory optimization - Observer will disconnect once component reached viewport/unmount

Installation

React Lazy Load requires React v16.8 or later.

npm install --save react-observer-api

Usage

1. Using Hook

isVisible will be true once DOM is visible in the viewport.
setElement need to pass it to the ref as shown below.

import { useVisibilityHook } from 'react-observer-api';

export default () => {
    const { setElement, isVisible } = useVisibilityHook();

    useEffect(() => {
        if (isVisible) {
            ...Logics/API call can trigger by watching isVisible property
        }
    }, [isVisible])

    return {
        <div ref={setElement}>
            {isVisible && (
                <>
                    ...Component need to render goes here....
                <>
            )}
        </div>
    }
}

Config Options - Optional

It allow to pass config options as param (optional).

{
    root: null,
    rootMargin: '0px',
    threshold: 1.0,
    always: false
}

For more details about options and usage, Click here

import { useVisibilityHook } from 'react-observer-api';

export default () => {
    const { setElement, isVisible } = useVisibilityHook({
        threshold: 0.5,
        rootMargin: '100px',
        always: false
    });
    ...
}

Always Observe

For some cases, you may want to continue to observe the dom node as it enters and exits the viewport. In this scenario, passing always: true in the config will enable this.

useVisibilityHook({ always: true });

<LazyLoad config={{ always: true }}>

Force Visible

For some case, based on condition/logic may need to show the dom before it reaches to viewport. In that scenario, by calling forceVisible() will load the dom.

import { useVisibilityHook } from 'react-observer-api';

export default () => {
    const { setElement, isVisible, forceVisible } = useVisibilityHook();

    useEffect(() => {
        forceVisible(); // isVisible become true, by manually calling this method.
    }, [])
    
    return {
        <div ref={setElement}>
            {isVisible && (
                <>
                    ...Component need to render goes here....
                <>
            )}
        </div>
    }
}

2. Using Component

The above same can achieved through Component as well. Need to wrap LazyLoad on top of the component for lazyloading

import { LazyLoad } from 'react-observer-api';

export default () => {
    
    return {
        <LazyLoad>
            <>...Component goes here....</>
        </LazyLoad>
    }
}

Optional Props

prop Type Default Description
options object { root: null, threshold: 0.25, rootMargin: '-10px', always: false } Click for more usage about options
as string div Wrapper element can be change by passing valid tag name. Ex: span / p / div
style object {} Custom CSS for wrapper element
forceVisible boolean false Passing true to render dom without waiting to reach the viewport

Example

import { LazyLoad } from 'react-observer-api';

export default () => {
    const style = {
        padding: 10
    };
    return {
        <LazyLoad as="span" style={style} forceVisible>
            <>...Component goes here....</>
        </LazyLoad>
    }
}

Note

For IE support, need to add polyfill

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

npm i 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')
        }
    }

Licence

MIT

react-lazyloading's People

Contributors

srigar avatar dependabot[bot] avatar williamholmes avatar tizmagik avatar

Watchers

James Cloos avatar  avatar

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.