React lazy loading with Intersection Observer API
MIT License
By combining the power of browser Intersection Observer API and React Lazy API I've created a simple component that will allow you to lazy load your component when it appears in the browser's viewport.
Don't load components that user won't see on the first render, React Laz-y will detect the scroll position for you and inject the correct code when it's actually needed.
To install, follow these few steps.
Before you start, make sure you use:
npm install npm@latest -g
npm i react-laz-y-component-loader
or
yarn add react-laz-y-component-loader
Pass a component imported with React.lazy
API as a children.
import React from 'react';
import ReactLazy from 'react-laz-y-component-loader';
const MyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<>
<header style={{ height: '300vh' }}>
<h1>My awesome title</h1>
</header>
<main>
<ReactLazy>
<MyComponent />
</ReactLazy>
</main>
</>
);
};
export default App;
rootMargin
propertyPass the rootMargin
props to increase or decrease the area of the root bounding box.
import React from 'react';
import ReactLazy from 'react-laz-y-component-loader';
const MyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<>
<header style={{ height: '300vh' }}>
<h1>My awesome title</h1>
</header>
<main>
<ReactLazy rootMargin="100px 0px">
<MyComponent />
</ReactLazy>
</main>
</>
);
};
export default App;
Name | Type | Default | Required | Description |
---|---|---|---|---|
children |
ReactElement |
undefined |
true |
Child element loaded with React.lazy API. |
onLoad |
function |
() => {} |
false |
Function that will be fired when child element is loaded. |
root |
HTMLElement |
viewport |
false |
Parent of the element that will be loaded. |
rootMargin |
string |
"0px" |
false |
Defines margin of root bounding box. See more here. |
threshold |
number || number[]
|
0 |
false |
Determines how much of the elements wrapper needs to intersect with the bounding box. See more here. |
fallback |
ReactElement |
<div>Loading...</div> |
false | Fallback element that will be rendered while target elements is being loaded. |
wrapperClass |
string |
"" |
false |
Custom class for element's wrapper. |
styles |
object |
{} |
false |
Custom styles for element's wrapper. |
Distributed under the MIT License. See LICENSE
for more information.
Maciek Grzybek - @maciek_g88 - [email protected]