n8tb1t / use-scroll-position Goto Github PK
View Code? Open in Web Editor NEWUse scroll position ReactJS hook done right
Home Page: https://n8tb1t.github.io/use-scroll-position/navbar/
License: MIT License
Use scroll position ReactJS hook done right
Home Page: https://n8tb1t.github.io/use-scroll-position/navbar/
License: MIT License
The current implementation gives you the scroll position only when scroll event happens but what if I need it as as soon as the page loads, as in the following example:
I have a Navbar that displays different according to its position:
When its a the top:
Any other position
But when I refresh the page, the scroll position is preserved, and once the page is fully loaded the right color couldn't be painted (Navbar is transparent):
I think the solution is just to attach the handleScroll function to the load event also
window.addEventListener('load', handleScroll);
I can submit a PR, let me know
> Build error occurred
/usr/app/node_modules/@n8tb1t/use-scroll-position/lib/index.js:1
export { useScrollPosition } from './useScrollPosition';
^^^^^^
SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:1116:16)
at Module._compile (internal/modules/cjs/loader.js:1164:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
at Module.load (internal/modules/cjs/loader.js:1049:32)
at Function.Module._load (internal/modules/cjs/loader.js:937:14)
at Module.require (internal/modules/cjs/loader.js:1089:19)
at require (internal/modules/cjs/helpers.js:73:18)
at Object.Mgi6 (/usr/app/.next/server/pages/[lng]/events.js:786:18)
at __webpack_require__ (/usr/app/.next/server/pages/[lng]/events.js:29:31)
at Module.qO+a (/usr/app/.next/server/pages/[lng]/events.js:2762:28) {
type: 'SyntaxError'
}
npm ERR! code
ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] build: `next build`
npm
Any suggestions? thank you
Npm v6.14.6
Next.js v9.5.2
For reference, here is a codesandbox.
I have a div
, which has content that is bigger than the div
's size. Therefore I made it scrollable using overflow: auto
. My question is, how can I track this div
s scroll position?
I tried doing this:
export default function App() {
const divRef = useRef();
useScrollPosition(
({ currPos }) => {
console.log(currPos); // never logs out, cause scroll progress of `div` isn't tracked
},
[],
divRef,
false,
300
);
return (
<div className="App">
<div
ref={divRef}
style={{
backgroundColor: "blue",
overflowY: "auto",
padding: "5px",
height: "300px"
}}
>
<div
style={{
backgroundColor: "red",
height: "2000px"
}}
/>
</div>
</div>
);
}
But this ref
approach doesn't work. Any help would be super appreciated!
Thank you for your awesome work. I'm curious if this library is still maintained since the latest commit is from 4 years ago and there is no activity for new issues and PRs. I wanted to fork and improve the api and logic but first, I wanted to ensure this project is not maintained anymore.
I see that useScrollPosition.defaultProps
is defined for some reason. It's a hook function and not a React component, so attaching a defaultProps
property to the function will not accomplish anything and is just extra noise.
Hi, I have tried to use your hook, it is elegant but on mobile (iphone) it does not account for scroll bounce behaviour and navbar stays hidden after the bounce.
I have tried to limit the state update -->
useScrollPosition(
({ prevPos, currPos }) => {
if(currPos.y >= 40){ // for scroll bounce problem (not working always)
let isShow = currPos.y > prevPos.y
if (isShow !== hideOnScroll ) setHideOnScroll(isShow)
}
},
[hideOnScroll],
null,
true,
300
)
Hey, awesome hook.
Having a small type issue and wondering if somehow I am just using it wrong.
Error is: Argument of type 'MutableRefObject<undefined>' is not assignable to parameter of type 'MutableRefObject<HTMLElement>'. Type 'undefined' is not assignable to type 'HTMLElement'.ts(2345)
I'm seeing this in a personal project but made a simple codesandbox to demonstrate the issue:
https://codesandbox.io/s/pensive-elion-ined1
Thanks!
It looks like you forgot to include the typings in the NPM package! ๐
The methods this uses to get scroll position are not compatible with IE11.
hi. i am developing a react app and I need to listen on scroll position changes and do specific things. i am using this library as it says in documentation. but it is not working and I don't get log statement in console. i read another issue about this problem and even my import statement is correct.
you can see my code here.
can you help me with this?
I'm new to react hooks, so I could very well be doing something wrong, but I cannot get even the console.log example to work. I'm using gatsby and react 16.12.0. I have a page called "scrollPage". the code is pasted below:
import React from "react";
import useScrollPosition from "use-scroll-position";
const ScrollPage = () => {
useScrollPosition(({prevPos, currPos}) => {
console.log(currPos.x);
console.log(currPos.y);
}, [], false, true, 10);
return (
<div>
<div>Hello Scroll Position</div>
<div style={{height: "2000px"}}></div>
</div>
)
}
export default ScrollPage;
I don't get any errors, just not logs to console. This hook is really convenient. Would love to get it working.
I am having a hard time writing a test for my component that uses useScrollPosition.
import { useScrollPosition } from "@n8tb1t/use-scroll-position";
import cx from "classnames";
import * as React from "react";
const MyComponent: React.FC<Props> = () => {
const [isScrolled, setIsScrolled] = React.useState(false);
useScrollPosition(
({ currPos }) => {
setIsScrolled(currPos.y <= -60);
},
[isScrolled]
);
return (
<div className={cx(isScrolled && outerWrapperScrolled)}>
...
</div>
);
};
export default MyComponent;
and I want to test it like this:
it("should render the outer wrapper with the className outerWrapper if user has scrolled more than 60px", () => {
const wrapper = shallow(<ScheduleHeaderWrapper {...props} />);
// ....
expect(wrapper).toHaveClassName("outerWrapper");
});
How can I mock useScrollPositon so that I can test my compontents behavior if currPos.y
is greater or equal then 60?
I had a problem when I wanted to detect the scroll stops, because when the state updates it stops my scroll so I made a solution to detect scroll stop if you want I can show you and make a PR
In my jest test environment there is no window. So useScrollPosition
throws with ReferenceError: window is not defined
. See #2.
First of all, congrats on the module. Found it on dev.to and the code is really clean. You should make it available on npm as well.
When deps change add new event listeners but don't remove the old event listeners .so if deps change multiple times we will have many event listeners
IE 11 gives console error "SCRIPT1002: Syntax error."
Hi, just wondering what the call signature would look like if we want to use a bounding element?
It seems that getBoundingClientRect
is called even when useWindow
is true
.
use-scroll-position/src/useScrollPosition.jsx
Lines 11 to 15 in c5d538b
I think we only want to call getBoundingClientRect
if useWindow
is false
? IIUC, getBoundingClientRect
will force layout, whereas window.scroll{X,Y}
will not.
I can't get negative numbers using this for when the scroll position is less than 0, when the user has overscrolled
Argument of type 'MutableRefObject<HTMLElement | null>' is not assignable to parameter of type 'MutableRefObject<HTMLElement | undefined>'.
Type 'HTMLElement | null' is not assignable to type 'HTMLElement | undefined'.
Type 'null' is not assignable to type 'HTMLElement | undefined'.ts(2345)
I'm using the following code and still getting the following error. Am I doing something wrong?
// Layout scroll position
if (!isServer) {
useScrollPosition(({ prevPos, currPos }) => {
console.log('Scroll prevPos', prevPos)
console.log('Scroll currPos', currPos)
// setElementPosition(currPos)
}, [], layoutRef, true)
How can i use this lib to know if the scroll is in the bottom of page
Hey there, I noticed that use-scroll-position isn't working if it is placed under a component with overflowY: 'scroll'
useScrollPosition(
({ prevPos, currPos }) => {
const goingDown = currPos.y < prevPos.y
const isBottom = currPos.y * -1 >= height - windowHeight - 20 // 20 is margin of error
const isTop = currPos.y * 1 == 0 + 100
if (isTop) {}
if (isBottom) {}
},
[height],
elementRef,
false,
parentRef
)
<div style={{ overflowY: 'scroll', height: '100vh' }} >
<div ref={parentRef}>
<div ref={elementRef}>
<ComponentWithLongContent />
</div>
</div>
</div>
I need the component to be wrapped in overflow parent because the component is one of the full page scrolling sections.
Any idea what's the remedy for this? Thanks!
All the deps are up to date, and yet we have a wrong warning that 100+ of them are out of date, probably img.shields.io or libraries.io have a bug...
Hi!
First of all thank you for creating this hook, it really adds a lot of value!
The TypeScript types appear to have some issues. The x and y coordinates should use number
instead of the upper-case Number
to allow for arithmetic operations.
I can create a pull request if you'd like.
Best regards,
Peter
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.