Giter VIP home page Giter VIP logo

rrr-lazy's Introduction

rrr-lazy

Lazy load component with react && react-router.

CircleCI dependency status

Installationg

rrr-lazy requires React 16.2.0 or later.

For npm:

npm install rrr-lazy

For yarn:

yarn add rrr-lazy

IntersectionObserver is required by this library. You can use this polyfill for old browsers https://github.com/w3c/IntersectionObserver/tree/master/polyfill

Usage

Use as a common lazy component

import React from 'react';
import { Lazy } from 'rrr-lazy';

const MyComponent = () => (
  <div>
    <Lazy
      rootMargin="300px 0 300px 0"
      render={(status) => (
        if (status === 'unload') {
          return <div>Unload</div>
        }
        if (status === 'loading') {
          return <div>Loading</div>
        }
        if (status === 'loaded') {
          return (
            <img
              style={{ height: 762, width: 1024 }}
              src={ status === 'loaded' ? 'http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg' : `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg"/>')}`}
            />
          );
        }
        throw new Error('Unknown status');
      )}
    />
  </div>
);

Loading data or do something else with lifecycle hooks

import { lazy } from 'rrr-lazy';

async function onLoading() {
  // Loading data;
  // ...
  return data;
}
async function onLoaded() {
  // Do something on loaded
  // ...
  return result;
}

async function onUnload() {
  // Do something on unload
  // ...
  return result;
}

async function onError(error) {
  // Do something on error
  console.error(error);
  // ...
  return result;
}

class App extends React.Component {
  render() {
    // the matched child route components become props in the parent
    return (
      <Lazy
        rootMargin="300px 0 300px 0"
        render={(status) => (
          if (status === 'unload') {
            return <div>Unload</div>
          }
          if (status === 'loading') {
            return <div>Loading</div>
          }
          if (status === 'loaded') {
            return (
              <img
                style={{ height: 762, width: 1024 }}
                src={ status === 'loaded' ? 'http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg' : `data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg"/>')}`}
              />
            );
          }
          throw new Error('Unknown status');
        )}
        onLoading={onLoading}
        onLoaded={onLoaded}
        onUnload={onUnload}
        onError={onError}
    />
    )
  }
}

API: <Lazy root rootMargin render loaderComponent loaderProps onError onLoaded onUnload onUnloaded />

Props

root

Type: String|HTMLElement Default: null

This value will be used as root for IntersectionObserver (See root.

rootMargin

Type: String Default: null

This value will be used as rootMargin for IntersectionObserver (See rootMargin.

render(status, props)

Type: Function Required

status can be unload, loading, loaded.

props are props that passed from Lazy. This is designed for @lazy, and when you use <Lazy> component, you may not need it.

loaderComponent

Type: string Default: div

laoderProps

Type: string Default: {}

loaderComponent and loaderProps is used to create a LoaderComponent when status is unload or loaded.

The result of render(status, props) will be passed to LoaderComponent as children.

onError()

onLoaded()

onLoading()

onUnload()

API: @lazy

Usage:

@routerHooks({
  fetch: async () => {
    await fetchData();
  },
  defer: async () => {
    await fetchDeferredData();
  },
})
@lazy({
  render: (status, props, Component) => {
    if (status === 'unload') {
      return <div style={{ height: 720 }}>Unload</div>;
    } else if (status === 'loading') {
      return <div style={{ height: 720 }}>Loading</div>;
    } else {
      return <Component {...props} />;
    }
  },
  onLoaded: () => console.log('look ma I have been lazyloaded!')
})
class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <img src='http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg' />
      </div>
    );
  }
}

Or

class MyComponent extends React.Component {
  render() {
    return (
      <div>
        <img src='http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg' />
      </div>
    );
  }
}
const myComponent = lazy({
  render: (status, props, Component) => {
    if (status === 'unload') {
      return <div style={{ height: 720 }}>Unload</div>;
    } else if (status === 'loading') {
      return <div style={{ height: 720 }}>Loading</div>;
    } else {
      return <Component {...props} />;
    }
  },
  onLoaded: () => console.log('look ma I have been lazyloaded!')
})(MyComponent);

options

getComponent

With webpack 2 import()

const myComponent = lazy({
  render: (status, props, Component) => {
    if (status === 'unload') {
      return <div style={{ height: 720 }}>Unload</div>;
    } else if (status === 'loading') {
      return <div style={{ height: 720 }}>Loading</div>;
    } else {
      return <Component {...props} />;
    }
  },
  onLoaded: () => console.log('look ma I have been lazyloaded!'),
  getComponent: () => import('./MyComponent'),
})();

API: LazyProvider

You can optionally use LazyProvider and pass a version (such as location) to the value prop. All of the Lazy instances will be reset when version changed.

Example:

class Application extends React.Component {
  render() {
    // when pathname changed, all of the Lazy instances will be reset.
    const { pathname, children } = this.state;
    <LazyProvider value={pathname}>
      { children }
    </LazyProvider>
  }
}

LICENSE

MIT

rrr-lazy's People

Contributors

greenkeeper[bot] avatar kouhin 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

Watchers

 avatar  avatar  avatar

rrr-lazy's Issues

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

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.