Last active
February 23, 2018 01:47
-
-
Save cometkim/cb2d4ce627fa7c603abc9e83aa7b9fe7 to your computer and use it in GitHub Desktop.
React 스크롤에 반응하는 헤더 컴포넌트
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react' | |
import styled from 'styled-components' | |
import Link from 'gatsby-link' | |
import theme from 'utils/theme' | |
interface HeaderProps { | |
title: string | |
fixed?: boolean | |
} | |
interface HeaderState { | |
hide: boolean, | |
pageYOffset: number | |
} | |
export default class Header extends React.PureComponent<HeaderProps, HeaderState> { | |
static defaultProps: Partial<HeaderProps> = { | |
fixed: false, | |
} | |
state = { | |
hide: false, | |
pageYOffset: 0 | |
} | |
handleScroll = () => { | |
const { pageYOffset } = window | |
const deltaY = pageYOffset - this.state.pageYOffset | |
const hide = pageYOffset !== 0 && deltaY >= 0 | |
this.setState({ hide, pageYOffset }) | |
} | |
componentDidMount() { | |
if (!this.props.fixed) { | |
window.addEventListener('scroll', this.handleScroll) | |
} | |
} | |
componentWillUnmount() { | |
if (!this.props.fixed){ | |
window.removeEventListener('scroll', this.handleScroll) | |
} | |
} | |
render() { | |
return ( | |
<Container className={this.state.hide ? 'hide' : ''}> | |
<HomeLink to='/'>{this.props.title}</HomeLink> | |
</Container> | |
) | |
} | |
} | |
const Container = styled.header` | |
display: flex; | |
align-items: center; | |
margin: 0; | |
position: fixed; | |
width: 100%; | |
height: ${theme.headerHeight}; | |
background: #fff; | |
border-bottom: 1px solid ${theme.grayColor}; | |
transition: transform .5s ease; | |
z-index: 2; | |
&.hide { | |
transform: translateY(-${theme.headerHeight}); | |
} | |
` | |
const HomeLink = styled(Link) ` | |
position: absolute; | |
left: 20px; | |
text-decoration: none; | |
font-size: 24px; | |
font-weight: bold; | |
color: black; | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment