|
| 1 | +import React from 'react' |
| 2 | +import { cx } from 'emotion' |
| 3 | +import useIsInViewport from './use-is-in-viewport' |
| 4 | +import { box, button, inWindowViewport, outsideWindowViewport, visible } from './styles' |
| 5 | + |
| 6 | +export function SimpleElement() { |
| 7 | + const [isInViewport, childElToWatch] = useIsInViewport() |
| 8 | + const [hide, toggleHide] = React.useState(false) |
| 9 | + |
| 10 | + return ( |
| 11 | + <> |
| 12 | + <button |
| 13 | + className={button} |
| 14 | + onClick={() => toggleHide(h => !h)} |
| 15 | + data-testid="toggle-box-position" |
| 16 | + > |
| 17 | + {hide ? 'Show box' : 'Hide box'} |
| 18 | + </button> |
| 19 | + <div |
| 20 | + className={cx(box, { |
| 21 | + [inWindowViewport]: !hide, |
| 22 | + [outsideWindowViewport]: hide, |
| 23 | + [visible]: isInViewport |
| 24 | + })} |
| 25 | + data-testid="box" |
| 26 | + ref={childElToWatch} |
| 27 | + > |
| 28 | + <p>{isInViewport ? 'In viewport' : 'Out of viewport'}</p> |
| 29 | + </div> |
| 30 | + </> |
| 31 | + ) |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * This component forwards a ref to the child element being watched for intersection |
| 36 | + * with the viewport. Forwarding the ref to the child is not necessary. This is only |
| 37 | + * an example to show that you useIsInViewport preserves origin ref behaviour (ref/cb ref) |
| 38 | + * by returning a new wrapped ref to be passed to the child. |
| 39 | + * If the ref wasn't meant for the child and instead for its container, then passing the |
| 40 | + * forwarded ref as the `target` option isn't necessary. |
| 41 | + */ |
| 42 | + |
| 43 | +export const RefForwardingElement = React.forwardRef(function RefForwardingElement( |
| 44 | + { threshold = 10 }, // default value for threshold so that we don't pass it in as undefined |
| 45 | + ref |
| 46 | +) { |
| 47 | + const [isInViewport, childRef] = useIsInViewport({ |
| 48 | + target: ref, |
| 49 | + threshold // if threshold is passed as an option, it MUST be a number or number[] |
| 50 | + }) |
| 51 | + const [hide, toggleHide] = React.useState(false) |
| 52 | + |
| 53 | + return ( |
| 54 | + <> |
| 55 | + <button |
| 56 | + className={button} |
| 57 | + onClick={() => toggleHide(h => !h)} |
| 58 | + data-testid="toggle-box-position" |
| 59 | + > |
| 60 | + {hide ? 'Show box' : 'Hide box'} |
| 61 | + </button> |
| 62 | + <div |
| 63 | + className={cx(box, { |
| 64 | + [inWindowViewport]: !hide, |
| 65 | + [outsideWindowViewport]: hide, |
| 66 | + [visible]: isInViewport |
| 67 | + })} |
| 68 | + data-testid="box" |
| 69 | + ref={childRef} |
| 70 | + > |
| 71 | + <p>{isInViewport ? 'In viewport' : 'Out of viewport'}</p> |
| 72 | + </div> |
| 73 | + </> |
| 74 | + ) |
| 75 | +}) |
0 commit comments