useRef로 스크롤 조작하기
특정 div태그들에 직접 접근해서 해당 위치로 스크롤을 이동시키기 위해, ref를 사용했다.
사용 방법
1) 원하는 변수명으로 useRef() 선언
2) 선택하고자 하는 DOM node(virtual DOM element)에 ref 속성 추가
3) 필요한 곳에서 변수명.current로 꺼내 쓰기!
useRef에 하나의 element가 아니라, 리스트로 여러 개의 element를 넣을 수도 있다!
const tabRef = useRef([]);
.
.
.
<TabContents ref={el => (tabRef.current[0] = el)}>...</TabContents>
<TabContents ref={el => (tabRef.current[1] = el)}>...</TabContents>
<TabContents ref={el => (tabRef.current[2] = el)}>...</TabContents>
- 단, 사용할 때는 콜백 함수 형태로 넣어줘야한다. ( ref={} 내부에서 함수를 호출하면 인자로 DOM node가 들어온다. )
보통 element.scrollIntoView()와 같이 사용한다.
** 공식문서에보면
다른 요소의 레이아웃에 따라 위쪽 또는 아래쪽으로 완전히 스크롤되지 않을 수 있습니다
따라서 css로 고정 헤더를 줄 경우, position을 fixed를 줄 때와 sticky를 줄 경우 레이아웃 높이 확인해서 계산해야한다.
1) 해당 header의 높이와 window.scrollY 값 구해서 계산한다.
var node="select your element";
var yourHeight="height of your fixed header";
// scroll to your element
node.scrollIntoView(true);
// now account for fixed header
var scrolledY = window.scrollY;
if(scrolledY){
window.scroll(0, scrolledY - yourHeight);
}
2) scroll-margin-top CSS 속성 사용
: scroll-margin-top수직 스크롤 대상을 변경하여 대상 요소를 뷰포트 상단에서 멀어지게 한다.
* {
scroll-margin-top: 100px;
}
3) 고정 헤더의 offset을 사용한다.
var topOfElement = document.querySelector('#targetElement').offsetTop - 고정헤더의높이;
window.scroll({ top: topOfElement, behavior: "smooth" });
출처
How to create refs for items in a loop using useRef? · React
I know the value of the ref can be an array but don't know how or where children should be added to the array. I've tried pushing them in the body of the…
spectrum.chat
https://chanhuiseok.github.io/posts/react-7/
[React] ref란? - DOM에 직접 접근하기(useRef)
컴퓨터/IT/알고리즘 정리 블로그
chanhuiseok.github.io
React Hooks - useRef를 이용한 스크롤 이동
위 사진은 클론코딩을 진행한 클래스101의 클래스 상세페이지이다. 각각의 탭을 클릭하면 해당하는 위치로 이동을 하는데 처음에는 바로 화면이 바뀌길래 active tab인줄 알았다. 클론코딩을 진행
velog.io
React 특정 DOM으로 스크롤 이동시키기
ref 리액트에서 ref는 DOM에 직접 접근할 때 사용합니다. 저는 특정 div태그들에 직접 접근해서 해당 위치로 스크롤을 이동시키기 위해, 이 ref를 사용했습니다. import React, { useRef } from 'react'; function..
zih0.tistory.com
https://velog.io/@dosilv/ReactWeb-API-useRef-scrollIntoView
[React/Web API] useRef (+scrollIntoView)
프로젝트 중 만나게 된 useRef와 IntersectionObserver 정리하기 🍋✨⚡
velog.io
https://developer.mozilla.org/ko/docs/Web/API/Element/scrollIntoView
element.scrollIntoView - Web API | MDN
Element 인터페이스의 scrollIntoView() 메소드는 scrollIntoView()가 호출 된 요소가 사용자에게 표시되도록 요소의 상위 컨테이너를 스크롤합니다.
developer.mozilla.org
https://rotadev.com/using-scrollintoview-with-a-fixed-position-header-dev/
Using scrollIntoView with a fixed position header – Dev – RotaDEV.com
The best answers to the question “Using scrollIntoView with a fixed position header” in the category Dev. QUESTION: I have a site with a header set to position: fixed. On one of my pages, I use scrollIntoView(true) on an element. My problem is that whe
rotadev.com