반응형
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;
`
반응형
'공부 > React & Next.js' 카테고리의 다른 글
[React] React state안에 state 넣기 (0) | 2022.12.06 |
---|---|
[React] [리액트 에러 해결] Uncaught Error: Objects are not valid as a React child (found: [object Date]). If you meant to render a collection of children, use an array instead. (0) | 2022.11.28 |
CSS Grid, Flex (0) | 2022.11.21 |
[React] 배열 다룰 때 사용하는 함수 (0) | 2022.11.21 |
노마드 코더 Coin Tracker 챌린지 문제 (0) | 2022.11.14 |