React 특정 요소로 스크롤 이동

김형석·2023년 6월 26일
0

React

목록 보기
1/1

React에서 특정 요소로 스크롤 이동을 하게 하는 기능 구현시 사용할 수 있는 방법

scrollIntoView

Element의 인터페이스로, scrollIntoView()가 호출된 요소가 사용자에게 표시되도록 요소의 상위 컨테이너를 스크롤합니다.
MDN element.scrollIntoView

element.scrollIntoView();
element.scrollIntoView(alignToTop); // Boolean parameter
element.scrollIntoView(scrollIntoViewOptions); // Object parameter

사용하전 주의사항

https://caniuse.com/?search=scrollIntoView

IOS에서 behavior:'smooth'의 경우 15.4버전 이하는 지원하지 않는다...;

options

alignToTop (optional)

default value : scrollIntoViewOptions: {block: "start", inline: "nearest"}
boolean

  • true : 요소의 상단은 스크롤 가능한 조상요소의 보이는 영역 상단에 정렬됨. => default value와 일치
  • false : 요소의 하단은 스크롤 가능한 조상 요소의 보이는 영역 하단에 정렬됨. => scrollIntoViewOptions: {block: "end", inline: "nearest"}

behavior (optional)

스크롤을 즉시 적용할지 아니면 부드러운 애니메이션을 적용할지 결정.

  • smooth : 스크롤이 부드럽게 움직임.
  • instant : 스크롤이 단번에 즉시 적용.
  • auto : 스크롤 동작은 scroll-behavior의 계산된 값에 의해 결정됨.

block (optional)

수직 정렬을 정의
default value : start

  • start
  • center
  • end

inline (optional)

수평 정렬을 정의
default value : nearest

  • start
  • center
  • end
  • nearest

How To Use ?

const scrollCallBack = () =>{
  document.getElementById('scrollTarget').scrollIntoView()
}

//..

return (
	<>	
  		<button onClick={scrollCallBack}>Click Me!</button>
  		<div>We just Simple Text</div>
  		<div>Dummy Text</div>
  		<div id='scrollTarget'>Im Target Element</div>
  	</>
  )

behavior option (smooth)

 const handleClick = () => {
    document.getElementById('spider')?.scrollIntoView({ behavior: 'smooth' })
  }

적용시 아래와 같이 작동한다.

with useRef

const spiderRef = useRef<HTMLElement>(null)


const handleClick = () => {
    spiderRef?.current?.scrollIntoView({ behavior: 'smooth' })
  }

  return (
    <>
      <div>{id}</div>
      <div className={styles.container}>
        <button type='button' className={styles.scrollBtn} onClick={handleClick}>
          scroll To Spider-Man
        </button>

        <img
          className={styles.poster}
          src='elemental'
          alt='엘리멘탈'
        />
        <img
          className={styles.poster}
          src='ride-or-die'
          alt='분노의 질주: 라이드 오어 다이'
        />
        <img
          id='spider'
		  ref={spiderRef}
		  src='spider-man'
          className={styles.poster}
          alt='스파이더맨: 어크로스 더 유니버스'
        />
      </div>
    </>
  )

on js

See the Pen CSS dot pattern/grid background by Seoku (@hyeongseoku) on CodePen.


마치며

FE 작업을 하다보면 해당 기능을 쓸 일이 굉장히 많은것 같다.

본인의 경우에는 유저의 이탈율을 줄이기 위해 사용자로 하여금 입력되지 않은 필드 등으로 자동으로 이동시켜주는 작업을 진행했다.

해당 메소드를 유용하게 이용할 수 있을것 같고.
sessionStorage 등과 같이 조합하여 사용하면 페이지 이동시에도 해당 부분으로 스크롤 시킬 수 있다.

next js 에서 적용했던 내용인 만큼 따로 다루도록 하겠다.

본인이 많이 사용하는 option을 말하며 마치겠다.

scrollIntoView({ behavior: 'smooth' ,block: 'center'})

profile
코드로 소통하기 위해 힘쓰는 프론트엔드 개발자 입니다.

0개의 댓글