rrr-lazy
Lazy load component with react && react-router.
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
;; const MyComponent = <div> <Lazy rootMargin="300px 0 300px 0" render= 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,` /> ; throw 'Unknown status'; /> </div>;
Loading data or do something else with lifecycle hooks
import lazy from 'rrr-lazy'; { // Loading data; // ... return data;} { // Do something on loaded // ... return result;} { // Do something on unload // ... return result;} { // Do something on error console; // ... return result;} Component { // the matched child route components become props in the parent return <Lazy ="300px 0 300px 0" = = = = = /> }
<Lazy root rootMargin render loaderComponent loaderProps onError onLoaded onUnload onUnloaded />
API: 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()
@lazy
API: Usage:
@@Component{return<div><img src='http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg' /></div>;}
Or
Component{return<div><img src='http://apod.nasa.gov/apod/image/1502/HDR_MVMQ20Feb2015ouellet1024.jpg' /></div>;}const myComponent =MyComponent;
options
getComponent
With webpack 2 import()
const 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:
Component{// when pathname changed, all of the Lazy instances will be reset.const pathname children = thisstate;<LazyProvider value=pathname>children</LazyProvider>}
LICENSE
MIT