@foo-software/react-scroll-context
v0.0.27
Published
A React scroll context provider and consumer for detecting scroll position (scrollX, scrollY) and providing that data to child components.
Downloads
43
Maintainers
Readme
@foo-software/react-scroll-context
React Scroll Context exports a React context provider and consumer. It provides
window
scroll data to a consumer.
Install
npm
npm install @foo-software/react-scroll-context
yarn
yarn add @foo-software/react-scroll-context
Dependencies
Props
Exposed Context Consumer Data
Usage
Standard
import React from 'react';
import { ScrollProvider } from '@foo-software/react-scroll-context';
// replace `scroll-context` any name you like.
const Context = React.createContext('scroll-context');
const ScrollDisplay = () => (
<ScrollProvider
Context={Context}
>
<div>
<h1>Scroll it!</h1>
<Context.Consumer>
{({ scrollX, scrollY, isScrollingDown }) => (
<pre>
scrollX: {scrollX}
scrollY: {scrollY}
isScrollingDown: {isScrollingDown ? 'yes' : 'no'}
</pre>
)}
</Context.Consumer>
</div>
</ScrollProvider>
);
Class
import React, { Component } from 'react';
import { ScrollProvider } from '@foo-software/react-scroll-context';
// replace `scroll-context` any name you like.
const Context = React.createContext('scroll-context');
class ScrollDisplay extends Component {
static contextType = Context;
render() {
const { scrollX, scrollY, isScrollingDown } = this.context;
return (
<pre>
scrollX: {scrollX}
scrollY: {scrollY}
isScrollingDown: {isScrollingDown ? 'yes' : 'no'}
</pre>
);
}
}
const App = () => (
<ScrollProvider
Context={Context}
>
<div>
<h1>Scroll it!</h1>
<ScrollDisplay />
</div>
</ScrollProvider>
);
useContext
hook
import React, { useContext } from 'react';
import { ScrollProvider } from '@foo-software/react-scroll-context';
// replace `scroll-context` any name you like.
const Context = React.createContext('scroll-context');
const ScrollDisplay = () => {
const { scrollX, scrollY, isScrollingDown } = useContext(Context);
return (
<pre>
scrollX: {scrollX}
scrollY: {scrollY}
isScrollingDown: {isScrollingDown ? 'yes' : 'no'}
</pre>
);
};
const App = () => (
<ScrollProvider
Context={Context}
>
<div>
<h1>Scroll it!</h1>
<ScrollDisplay />
</div>
</ScrollProvider>
);
Credits
This package was brought to you by Foo - a website performance monitoring tool. Create a free account with standard performance testing. Automatic website performance testing, uptime checks, charts showing performance metrics by day, month, and year. Foo also provides real time notifications when performance and uptime notifications when changes are detected. Users can integrate email, Slack and PagerDuty notifications.