React-on-screen

Check if a react component in the viewport https://fkhadra.github.io/react-on-sc…

React on screen npm npm license Coverage Status

???? Check if your react component are visible on the screen without pain and with performance in mind ????!

react-on-screen-demo

Demo

View the demo.

Installation

$ npm install --save react-on-screen
$ yarn add react-on-screen

A UMD build is also available :

<script src="./dist/ReactOnScreen.min.js"></script>

Usage

Simple

import React from 'react';
import TrackVisibility from 'react-on-screen';

const ComponentToTrack = ({ isVisible }) => {
    const style = {
        background: isVisible ? 'red' : 'blue'
    };
    return <div style={style}>Hello</div>;
}

const YourApp = () => {
    return (
       {/* Some Stuff */}
        <TrackVisibility>
            <ComponentToTrack />
        </TrackVisibility>
       {/* Some Stuff */}
    );
}

Using a render props

You can use a render props is you want to !

const YourApp = () =&gt; {
    return (
        
            {({ isVisible }) =&gt; isVisible &amp;&amp; }
        
    );
}

Track the visibility only once

For many cases you may want to track the visibility only once. This can be done simply as follow :

const YourApp = () =&gt; {
    return (
        
            
        
    );
}

Defining offset

Using offset props can be usefull if you want to lazy load an image for instance.

const YourApp = () =&gt; {
    return (
        
            {({ isVisible }) =&gt; isVisible ?  : }
        
    );
}

Partial visibility

You may want to consider that a component is visible as soon as a part of the component is visible on screen. You can use the partialVisibility props for that.

const YourApp = () =&gt; {
    return (
        
            {({ isVisible }) =&gt; }
        
    );
}

Use the html tag of your choice

const YourApp = () =&gt; {
    return (
        
            {({ isVisible }) =&gt; }
        
    );
}
View on GitHub

Subscribe to the Newsletter

Get our latest news,tutorials,guides,tips & deals delivered to your inbox.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

shares