Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add usage example using React Hooks #268

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,52 @@ class SomeOtherComponent extends React.Component {
```


##### React Hooks/ES6 with Refs

```javascript
// 1. Import the functions
import { disableBodyScroll, enableBodyScroll, clearAllBodyScrollLocks } from 'body-scroll-lock';

const SomeComponent = () => {
// 2. Initialise your state and ref here
const [open, setOpen] = useState(false)
const ref = useRef(null)

useEffect(() => {
// 3. Check for the target element that you want to persist scrolling for (such as a modal/lightbox/flyout/nav).
// Specifically, the target element is the one we would like to allow scroll on (NOT a parent of that element).
// This is also the element to apply the CSS '-webkit-overflow-scrolling: touch;' if desired.

if (ref.current) {
if (open) {
// 4. Disable body scroll when open
disabledBodyScrollLock(ref.current)
} else {
// 5. Re-enable body scroll when closed
enableBodyScrollLock(ref.current)
}
}

return () => {
// 5. Useful if we have called disableBodyScroll for multiple target elements,
// and we just want a kill-switch to undo all that.
// OR useful for if the `hideTargetElement()` function got circumvented eg. visitor
// clicks a link which takes him/her to a different page within the app.
clearAllBodyScrollLocks()
}
}, [open])

// 6. Pass your ref to SomeOtherComponent
return (
<SomeOtherComponent ref={ref}>
{/* some JSX to go here */}
</SomeOtherComponent>
);
}
}
```


##### Angular

```javascript
Expand Down