Ref realizes navigation and rolling positioning
Keywords:
Javascript
React
Attribute
abstract
In development projects, there is often a need to click jump to scroll to the anchor. The simplest anchor location is to give a tag a, a tag's href = 'anchor', and then give an id = 'anchor' to the anchor to jump. Referring to the simplest way to realize the jump of anchor point, useRef is used in React to realize the function of jump of anchor point.
Function specific steps
1. Create an empty Ref
import React, { useRef } from 'react';
const Layout = () => {
const pageTopRef = useRef(null);
const sectionEventInfoRef = useRef(null);
return (
<div>Scrolling content</div>
)
}
export default Layout;
2. Jump anchor function
Element.scrollIntoView The () method scrolls the current element into the viewable area of the browser window. We can use this method with Ref to realize the function of jump anchor. The behavior attribute can define the animation transition effect, and the rolling effect is smoother when jumping anchor. The specific code is as follows:
// Click the navigation button to scroll to the corresponding area in the page
const handleClickNavItem = ref => {
setIsWork(false);
if (ref.current) {
ref.current.scrollIntoView({ behavior: "smooth" });
}
}
3. Anchor point
bind() binds ref, and the anchor is in the binding corresponding jump Ref. the simplified code is as follows:
import React, { useRef } from 'react';
import '../style.scss';
const Layout = () => {
const pageTopRef = useRef(null);
const sectionEventInfoRef = useRef(null);
// Click the navigation button to scroll to the corresponding area in the page
const handleClickNavItem = ref => {
setIsWork(false);
if (ref.current) {
ref.current.scrollIntoView({ behavior: "smooth" });
}
}
return (
<div className="activity-area">
<div className="actAr-wrapper">
<div className="actAr-tabs">
<button onClick={handleClickNavItem.bind(null, pageTopRef)}>home page</button>
<button onClick={handleClickNavItem.bind(null, sectionEventInfoRef)}>Event details</button>
<button onClick={openEWorks}>Selected works</button>
</div>
<div className="actAr-content">
<!-- Anchor point one -->
<div ref={pageTopRef}>
//Back to home anchor
</div>
<!-- Anchor point 2 -->
<div ref={sectionEventInfoRef}>
//Anchor point for event details
</div>
</div>
</>
</div>
)
}
export default Layout;