리액트 라우터 4에서의 앵커태그 사용
사용자가 앵커 링크를 통해 페이지로 이동할 때 페이지가 내 앵커 태그까지 스크롤되도록 합니다.
리액트 라우터 4를 사용하고 있으며, 다음과 같이 정의했습니다.
네비게이션 바:
export default (props) => {
const {
updateModal,
updateRoute,
} = props
return(
<Navbar fluid collapseOnSelect>
<Nav>
<NavDropdown eventKey="4" title="Solutions" id="nav-dropdown" noCaret>
<MenuItem eventKey="4.1">
<Link to='/solution#ipos'>TESTING ANCHOR</Link>
</MenuItem>
...
일부 루트:
export default class extends Component {
constructor() {
super()
this.state = {
isLoading: true
}
}
render() {
return (
<Grid className='solutions' fluid>
<Row className='someClass'>
<div>
<h2><a href='ipos' id='ipos'>Ipos morna santos paros</a></h2>
...
navebar의 앵커링크를 클릭하면 URL과 레독스스토어에 해시 앵커태그가 표시되어 새로운 루트로 이동하지만 태그 자체로는 스크롤 다운되지 않습니다.
스크롤 기능을 만드는 것은 저에게 달려있습니까, 아니면 정확히 어떻게 작동해야 합니까?
앵커 태그까지 스크롤 다운하려면 다음과 같이 React Router Hash Link를 설치해야 합니다.
npm install --save react-router-hash-link
다음으로 해시 링크를 Import합니다.
import { HashLink as Link } from 'react-router-hash-link';
해시 링크를 사용합니다.다음은 예를 제시하겠습니다.
<Link to="/pathLink#yourAnchorTag">Your link text</Link>
대상 컴포넌트에는 다음과 같은 것이 있습니다.
<div id= "yourAnchorTag">
<p>Linked to here<p>
</div>
리액트 라우터의 기존 문제입니다.(https://github.com/ReactTraining/react-router/issues/394#issuecomment-220221604)
해결책도 있다.https://www.npmjs.com/package/react-router-hash-link 이 패키지는 문제를 해결합니다.
이거 써야 돼Hash Link처럼Link아래와 같이.
import { HashLink as Link } from 'react-router-hash-link';
예측 가능한 앵커링크가 거의 없는 경우 정상적인 동작을 실현하는 가장 간단한 방법은scrollIntoView()필요한 앵커 태그가 있는 경우 요소의Window.location.href.
class Page extends react.Component {
componentDidMount() {
if (this.$ref && location.href.includes('#my-ref')) {
this.$ref.scrollIntoView({
// optional params
behavior: 'smooth',
block: 'start',
inline: 'center',
});
}
}
render() {
return (
// This is the div you want to scroll to
<div ref={ref => {
this.$ref = ref;
}}>
Other content
</div>
);
}
}
Element.scrollIntoView() 및 React refs를 체크합니다.
다음과 같이 Link에 개체를 전달할 수 있습니다.
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
참조: https://reacttraining.com/react-router/web/api/Link
@filippo와 비슷하지만 리액트 훅과 약간의 Typescript가 있습니다.
import React, { Functioncomponent, useEffect, useRef } from 'react';
import { useLocation } from 'react-router-dom';
const MyFunc: FunctionComponent = () => {
const myRef = useRef<null | HTMLDivElement>(null);
useEffect(() => {
if (myRef && location.hash.includes('#my-ref')) {
myRef?.current?.scrollIntoView({
behavior: 'smooth',
block: 'start',
inline: 'center'
});
}
}, [myRef, location.hash]);
return (
<div> Some stuff before </div>
<div ref={myRef}> Scroll to me </div>
<div> Some stuff after </div>
)
}
export default MyFunc;
앵커 태그에서 해시 fragment를 사용하는 대신 DOM을 쿼리하여scrollIntoView()의 일부로서onClick이벤트입니다.
function handleClick(evt) {
...
document.querySelector('[id="label-input-1"]').scrollIntoView();
}
...
<a href={''} onClick={e => handleClick(e)}>Foo</a>
이 조작에서는 윈도 로케이션이 해시 주소로 갱신되었을 때 라우터가 페이지를 새로 고치는 것을 회피할 뿐입니다.
전 개츠비를 이용했고, 제 해결 방법은@reach/router다음 형식으로.
import { navigate } from '@reach/router';
navigate('#some-link');
언급URL : https://stackoverflow.com/questions/48223566/using-anchor-tags-in-react-router-4
'programing' 카테고리의 다른 글
| "wp_insert_post"를 실행하기 전에 게시물의 제목이 존재하는지 확인하여 게시물의 중복을 방지하는 Word press 방법 (0) | 2023.03.26 |
|---|---|
| Mongo: 특정 필드가 없는 항목 찾기 (0) | 2023.03.26 |
| 속성에 경로를 지정하여 클래스 속성을 JSON의 하위 속성에 매핑할 수 있습니까? (0) | 2023.03.26 |
| 여러 메타 키로 주문하는 방법 (0) | 2023.03.26 |
| 리액트 부트스트랩이 리액트 컴포넌트를 스타일링하지 않음 (0) | 2023.03.26 |