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>
Specifies the mechanism for internal execution.
- scrollIntoView: use element.scrollIntoView api
- scrollTop: use element.scrollTop api
Url search key for the anchor, default is '_to'.
Options passed when scrollIntoView is used.
Specifies which element performs scrollTop, if not, scrollTop is set by default using one of the following options:
- document.body.scrollTop
- document.documentElement.scrollTop
- window.pageYOffset
note: This option is the parameter for the document.querySelector, so choose the type it supports.
Specifies the distance from the top, which defaults to 0. The actual scrollTop equals:
document.querySelector(container).scrollTop = document.getElementById(anchor).offsetTop + interval
MIT