https://github.com/rockchalkwushock/custom-scroll
Repository for showing the current state of scrolling when using shallow routing in Next.js
https://github.com/rockchalkwushock/custom-scroll
nextjs react-scroll
Last synced: 4 months ago
JSON representation
Repository for showing the current state of scrolling when using shallow routing in Next.js
- Host: GitHub
- URL: https://github.com/rockchalkwushock/custom-scroll
- Owner: rockchalkwushock
- Created: 2017-07-09T14:29:13.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2017-07-09T16:16:55.000Z (over 8 years ago)
- Last Synced: 2025-04-09T19:52:10.593Z (10 months ago)
- Topics: nextjs, react-scroll
- Language: JavaScript
- Size: 860 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Custom-Scroll
## Usage
```bash
git clone https://github.com/rockchalkwushock/custom-scroll.git
cd custom scroll
yarn
yarn dev # application will run on localhost:3000
```
## The Problem
Currently with the way `next` is handling shallow routing a built-in function handles a scroll event to the hashed element:
```js
// Using shallow prop on Link.
import Link from 'next/link'
// Using Router with shallow option
_handleClick = (e, el) => {
e.preventDefault()
e.stopPropagation()
const href = `/#${el}`
Router.push(href, href, { shallow: true })
}
// Both methods will 'scroll' to this div.
```
This works fine when just using `next`'s native scrolling event; however when creating custom scroll events or using a third party library like `react-scroll` there is no way to override the native scrolling event that is part of the shallow routing feature.
The following is an example of what a user can expect when trying to accomplish shallow routing and using a custom scroll event:

## The Solution
Feature add for user to pass custom scroll events to [`scrollToHash`](https://github.com/zeit/next.js/blob/v3-beta/lib/router/router.js#L265)
```js
Router.push(href, href, { shallow: true, custom: { scroll: true, event: el => scrollTo(el) })
async change (method, _url, _as, options) {
// ...
if (this.onlyAHashChange(as)) {
this.changeState(method, url, as)
this.scrollToHash(as, options)
return
}
// ...
scrollToHash (as, options) {
const [ , hash ] = as.split('#')
const el = document.getElementById(hash)
// Check for customScroll event passed by user
// FIXME: Might be better to check that the key is present first to avoid 'undefined' issue.
if (options.custom.scroll) {
// If present use it as the scroll event on routing.
options.custom.event(el)
} else {
// If no customScroll present default to predefined
// scroll method provided by `next`.
el.scrollIntoView()
}
}
}
```