react-stay-in-view
v1.2.0
Published
A react hook and component to create popper (popover) that never leave the screen.
Downloads
13
Maintainers
Readme
react-stay-in-view
A react hook and component to create popper (popover) that never leave the screen. Created elements will not disappear from the screen when scrolling and resizing.
Features
- 🚀 Fast - Built with hooks and functional components only.
- 🛠 Written in TypeScript - It'll fit right into your existing TypeScript project.
- 👫 Cross-browser - Works out-of-the-box for most browsers, regardless of version.
- 📲 Mobile-friendly - Supports mobile devices and touch screens.
- 🌳 Tree-shakeable - Only include the parts you use.
- 🗜 Lightweight - Around
~1.1kB
. - 💨 No dependencies
Install
# with npm
npm install --save react-stay-in-view
# with yarn
yarn add react-stay-in-view
Usage
useStayInView
hook
import { useStayInView } from 'react-stay-in-view';
const StayInView = ({ className, children, anchorEl, placement }) => {
const { ref } = useStayInView({ anchorEl, placement });
return (
<div ref={ref} className={className}>
{children}
</div>
);
};
Props
Output: ref
- paste this ref
in your component
| Name | Description | Type | Required | Default Value |
| ------------------ | -------------------------------------------------------------------- | ------------- | -------- | ------------- |
| anchorEl | An element relative to which the new position will be fixed | HTMLElement
| | null
|
| placement | Element position relative to anchorEl
| string
| | right-start
|
| avoidAnchorOverlap | Prevents anchorEl
from overlapping when scrolling to screen border | boolean
| | true
|
StayInView
component
import { StayInView } from 'react-stay-in-view';
const App = () => {
const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
const [isVisible, setIsVisible] = useState<boolean>(false);
const onClick = (e: React.MouseEvent<HTMLButtonElement>) => {
setAnchorEl(e.currentTarget);
setIsVisible((prev) => !prev);
};
return (
<div>
{isVisible && (
<StayInView anchorEl={anchorEl}>
<div>I stay on the screen</div>
</StayInView>
)}
<button onClick={onClick}>Click me!</button>
</div>
);
};
Props
| Name | Description | Type | Required | Default Value |
| ------------------ | -------------------------------------------------------------------- | ------------- | -------- | ------------- |
| children | A children element | ReactNode
| ✅ | |
| className | Container class name. | string
| | null
|
| anchorEl | An element relative to which the new position will be fixed | HTMLElement
| | null
|
| placement | Element position relative to anchorEl
| string
| | right-start
|
| avoidAnchorOverlap | Prevents anchorEl
from overlapping when scrolling to screen border | boolean
| | true
|
Contributions
Learn how to contribute