intersection observed
[](https://www.npmjs.com/package/@nju33/react-intersection-observed])
Install
yarn add @nju33/react-intersection-observed
yarn add react react-dom @types/react @types/react-dom
Example
import intersectionObservedFactory = require('@nju33/react-intersection-observed');
import {
IntersectionObservedProps,
IntersectionObservedComponent,
IntersectionObserved
} from '@nju33/react-intersection-observed';
interface FooProps {
foo: string;
}
type FooIntersectionProps = FooProps & IntersectionObservedProps
class Foo extends React.Component<FooIntersectionProps>
implements IntersectionObservedComponent {
render() {
return <div ... />;
}
// optional
componentOnEnter() {
console.log('componentOnEnter');
}
// optional
componentOnceEnter() {
console.log('componentOnceEnter');
}
// optional
componentOnLeave() {
console.log('componentOnLeave');
}
// optional
componentOnceLeave() {
console.log('componentOnceLeave');
}
componentWillUnmount() {
this.props.intersectionObserved.unobserve();
}
}
const intersectionObserved = intersectionObservedFactory();
const IntersectionObservedFoo = (intersectionObserved as IntersectionObserved<FooProps>)(Foo);
<IntersectionObservedFoo foo="foooo" />
With the StyledComponents
If you have used styled-components, you've to apply intersectionObserved
earlier than styled
.
e.g.
const IntersectionObservedFoo = (intersectionObserved as IntersectionObserved<
FooProps
>)(Foo);
const styledFoo = styled(IntersectionObservedFoo);
<styledFoo foo="fooooo" />;
Customize
you can adjust determine when an element entered into the view.
For that you've to set the isEnter
function in the argument object of the intersectionObservedFactory
.
// intersectionObservedFactory({
// isEnter(entry: IntersectionObserverEntry): boolean;
// })
intersectionObservedFactory({
isEnter(entry: IntersectionObserverEntry) => entry.intersectionRatio !== 0;
})