Skip to content

Declarative way to listen to scroll and resize events of the viewport

Notifications You must be signed in to change notification settings

hssrrw/react-viewport-observer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React Viewport Observer

Declarative way to listen to scroll and resize events of the viewport.

Installation

npm install --save react-viewport-observer

or

yarn add react-viewport-observer

Why

Typcal use cases are scroll controlled effects and viewport size monitoring.

This project prevents from creating multiple event listeners, allowing to 'subscribe' to viewport events in a declarative way.

Usage

// App.js
import { ViewportStore, ViewportBroadcaster } from 'react-viewport-observer';

const viewportStore = new ViewportStore();
const App = () =>
	<ViewportBroadcaster store={viewportStore}>
		{/* some children */}
	</ViewportBroadcaster>;
// ScrollProgress.js
import { ViewportSubscriber } from 'react-viewport-observer';

const ScrollProgress = () =>
	<ViewportSubscriber fields={['scrollPercent']}>
		{/* fields can be: scrollY, scrollPercent, width, height */}
		{({ scrollPercent }) =>
			{/* some fancy scroll effect like scaling :D */}
			<div style={{ transform: `scaleX(${scrollPercent / 100})` }} />}
	</ViewportSubscriber>;

License

MIT

About

Declarative way to listen to scroll and resize events of the viewport

Resources

Stars

Watchers

Forks

Packages

No packages published