An anchor react component use query string without hash. 一个使用 query string来实现 hash 功能的 react 组件。
English | 简体中文
A anchor react component use url search string without hash.
This component solves the problem that hash anchors cannot be used when using the hash router.
This is a good solution for projects that need to use hash routing compatible with older browsers (IE9) but want to use anchor points
https://kwzm.github.io/react-anchor-without-hash/
https://codesandbox.io/embed/react-anchor-without-hash-2xq2h
$ npm i react-anchor-without-hash
The effect is the same as scrollIntoView).
When url search includes ‘_to=section1’, the section1 will scroll into view area.
import Anchor from 'react-anchor-without-hash'
// ......
<Anchor name="section1">
<div className="section section1">
<h2>This is section1</h2>
<div>There are some text...</div>
</div>
</Anchor>
<Anchor name="section2">
<div className="section section2">
<h2>This is section2</h2>
<div>There are some text...</div>
</div>
</Anchor>
The effect is the same as scrollTop).
When url search includes ‘_to=section1’, the section1 will scroll into view area with 50px top margin.
note:
1.Because offsetTop is used internally to get the height of the scroll, you need to make sure have a positioned containing element.
2.Interval can allow negative values
import Anchor from 'react-anchor-without-hash'
// ......
const anchorProps = {
type: 'scrollTop',
container: '#container',
interval: 50
}
<div style={{position: 'relative'}}>
<Anchor name="section1" {...anchorProps}>
<div className="section section1">
<h2>This is section1</h2>
<div>There are some text...</div>
</div>
</Anchor>
<Anchor name="section2" {...anchorProps}>
<div className="section section2">
<h2>This is section2</h2>
<div>There are some text...</div>
</div>
</Anchor>
</div>
type: string
Specifies the mechanism for internal execution.
anchorKey: string
scrollIntoViewOption: boolean | object
container: string
note: This option is the parameter for the document.querySelector, so choose the type it supports.
interval: number
Specifies the distance from the top, which defaults to 0.
The actual scrollTop equals:
document.querySelector(container).scrollTop = document.getElementById(anchor).offsetTop + interval
License
MIT