2023. 1. 2. 16:41ㆍreact
구현하고자 하는 기능
해당 영역에 스크롤이 도착하면 원하는 애니메이션이 작동하는 클래스를 토글시키기
사용
element.getBoundingClientRect()
DOM요소의 크기와 브라우저 뷰포트를 기준으로 상대적인 위치에 대한 정보를 제공 하는 객체를 반환합니다.
getBoundingClientRect는 화면에서 잡은 dom이 어디에 위치한 지 알기 위해 사용합니다.
return값은 해당 dom의 width, height, top, left, right, bottom, x, y이며 width와 height는 뷰포트 왼쪽 상단을 기준으로 한다.
useRef()
react에서는 querySelector 등의 dom을 선택할 수 있는 메서드를 사용할 수 없기때문에 이를 대신하는 useRef()로 dom을 선택한다. (남용하면 안된다는 내용도 있으므로 추가 검색 추천)
import React, { useState, useEffect, useRef } from 'react';
const scrollEvent = () => {
const [toggleScroll, setToggleScroll] = useState(false);
const scrollRef = useRef(null);
useEffect(() => {
if(!scrollRef.current) retrurn;
window.addEventListener('scroll', toggleScrollEvent);
return() => {
window.removeEventListener('scroll', toggleScrollEvent);
};
}, [scrollReg.currnet]);
const toggleScrollEvent = () => {
const toggleScrollH = scrollRef.current.getBoundingClientRect().top;
const toggleScrollB = whatIsRef.current.getBoundingClientRect().bottom;
setWhatIsScroll(window.innerHeight > toggleScrollH + 100 && window.innerHeight < toggleScrollB + 700 );
};
return(
<>
<section className={toggleScroll ? 'scroll active' : 'scroll'} ref={scrollRef}>
<p>
이 섹션 영역에 스크롤이 들어오면 </br >
<span>여기</span>의 글씨가 커졌다 작아집니다.
</p>
</section>
</>
)
}
useRef를 이용하여 원하는 영역의 dom을 선택하고 해당 dom에 getBoundingClientRect 메소드를 실행하여 top 위치를 알아낸다.
toggleScrollEvent에는 조건을 2개 걸어 위, 아래에서 스크롤해도 active가 걸리도록 했다.
애니매이션이 들어가는 css에 .active를 붙이면 된다.
참고사이트
Element.getBoundingClientRect(), 뷰포트 기준으로 엘리먼트 위치 알아내기, viewport, javascript, js, getElementBy
Element.getBoundingClientRect(), 뷰포트 기준으로 엘리먼트 위치 알아내기, viewport, javascript, js, getElementById, react 예시
kyounghwan01.github.io
https://al-coding.tistory.com/6
스크롤 이벤트_fade In(페이드인)(vanilla js + css)
/* Scroll Animation (sa, 스크롤 애니메이션) */ 위에서 아래로 이해하기 for...of 명령문은 반복가능한 객체 (Array, Map, Set, String, TypedArray, arguments 객체 등을 포함)에 대해서 반복하고 각 개별 속성값에 대
al-coding.tistory.com
'react' 카테고리의 다른 글
react-scroll-trigger을 사용하여 scroll on 됐을 때 Countup 실행하기 (0) | 2023.01.03 |
---|---|
react에서 fontawesome 사용하기 (0) | 2022.11.24 |
nomad code_react js로 영화앱 만들기_#7.0(To Do List part One) (0) | 2022.11.16 |
nomad code_react js로 영화앱 만들기_#6.4(Cleanup) (0) | 2022.11.16 |
nomad code_react js로 영화앱 만들기_#6.1 ~ 6.3 (0) | 2022.11.16 |