[React] scroll top 이동

bunny.log·2022년 7월 28일

버튼으로 브라우저 상단 이동

컴포넌트 버튼으로 만들어서 버튼을 누르면 브라우저 상단으로 이동

import React from 'react';
import styled from 'styled-components';

const Container = styled.button`
	position: fixed;
	top: 50%;
	right: 30px;
	width: 60px;
	height: 60px;
	transform: translateY(-50%);
	background-color: ${props => props.theme.dpBlue};
	border-radius: 50%;
	font-size: 14px;
	font-weight: bold;
	letter-spacing: -0.28px;
	text-align: center;
	color: #fff;
	box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.16);
	cursor: pointer;
	z-index: 99999;
`;

function ScrollTop(): JSX.Element {
	const handleClick = () => {
		if (!window.scrollY) return;
		// 현재 위치가 이미 최상단일 경우 return

		window.scrollTo({
			top: 0,
			behavior: 'smooth',
		});
	};

	return <Container onClick={handleClick}>TOP</Container>;
}

export default React.memo(ScrollTop);
profile
더 많은 유익한 내용은 ->> https://github.com/nam-yeun-hwa

0개의 댓글