공부/React & Next.js

[React] React 버튼 클릭 시 스크롤 이동 예제(useRef)

bumcrush 2022. 11. 26. 20:43
반응형
React 버튼 클릭 시 스크롤 이동하는 방법 (useRef)

- useRef 훅을 이용

- useRef : 특정 DOM을 가리킬 때 사용하는 Hook함수

 

리액트 버튼 클릭 시 스크롤 이동

 

리액트 버튼 클릭 시 스크롤 이동

 

 

import React, { useRef } from 'react';
import styled from 'styled-components';

function App() {
  /* 스크롤 이동 */
  const inputForm = useRef();  //특정 DOM을 가리킬 때 사용하는 Hook함수, SecondDiv에 적용
  const onMoveToForm = () => {
    inputForm.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div>
      <FirstDiv>
        <h1>버튼을 누르면 아래로 이동합니다.</h1>
        <button onClick={onMoveToForm}> 버튼 클릭 </button>
      </FirstDiv>
      <SecondDiv ref={inputForm}>
        <h1>이동 완료</h1>
      </SecondDiv>
    </div>
  );
}

export default App;

const FirstDiv = styled.div`
    height: 100vh;
    font-size: 20px;
    font-weight: bold;
    text-align : center;    
`

const SecondDiv = styled.div`
    height: 100vh;
    font-size: 20px;
    font-weight: bold;
    background: #e9ecef;
    text-align : center;
`

 

반응형