Skip to content

Instantly share code, notes, and snippets.

@jitinmaher
Last active November 25, 2018 16:08
Show Gist options
  • Save jitinmaher/7edacb24aeb162e88f77c8d428bb6120 to your computer and use it in GitHub Desktop.
Save jitinmaher/7edacb24aeb162e88f77c8d428bb6120 to your computer and use it in GitHub Desktop.
This gist creates a custom plug and play hook "useScrollListner" which accepts element id and changes the sticky behaviour of the node when user scrolls through the page
import React, { useEffect, useState } from 'react';
const fixedText = 'I am fixed :)';
const whenNotFixed = 'I am not a fixed header :(';
function handleStickyness( node, setText ) {
node.classList.add("sticky");
document.title = fixedText;
setText( fixedText );
}
function handleNormalBehaviour( node, setText ) {
node.classList.remove("sticky");
document.title = whenNotFixed;
setText( whenNotFixed );
}
function clearEventHandler( scrollCallBack ) {
window.removeEventListener( 'scroll', scrollCallBack );
}
export default function useScrollListner( nodeId ) {
const [ text, setText ] = useState( fixedText );
useEffect(() => {
const node = document.getElementById( nodeId );
const originalPosition = node.offsetTop;
const scrollCallBack = window.addEventListener('scroll', () => {
const sticky = node.offsetTop;
if (window.pageYOffset > sticky) {
handleStickyness( node, setText );
}
if( window.pageYOffset <= originalPosition ) {
handleNormalBehaviour( node, setText );
}
});
return clearEventHandler( scrollCallBack );
}, []);
return text;
}
/*
Functional component using `useScrollListner` custom hook
*/
function App() {
const headerText = useScrollListner("myHeader");
return (
<div>
<header className="header">HEADER</header>
<SomeRandomText />
<header id="myHeader" className="header">
{headerText}
</header>
<SomeRandomText />
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment