Skip to content

Instantly share code, notes, and snippets.

@WDever
Created February 24, 2020 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WDever/54139c1b043771e6cfbba87fd429625f to your computer and use it in GitHub Desktop.
Save WDever/54139c1b043771e6cfbba87fd429625f to your computer and use it in GitHub Desktop.
// style.tsx
import styled from 'styled-components';
import { Link } from 'gatsby';
import { pxToRem } from 'utils';
interface HeaderProps {
scrolled: boolean;
visibility: boolean;
}
export const Header = styled.header<HeaderProps>`
width: 100%;
height: ${pxToRem(56)};
display: flex;
justify-content: center;
transition: top 0.2s ease-in-out;
position: sticky;
top: ${({ visibility }): number | string => {
console.log('hey', visibility);
return visibility ? 0 : pxToRem(-56);
}};
z-index: 5;
background-color: ${({ theme }): string => theme.item};
box-shadow: ${({ scrolled, theme }): false | string =>
scrolled && theme.headerShadow};
`;
export const Inner = styled.div`
max-width: ${pxToRem(1392)};
width: 100%;
display: flex;
justify-content: space-between;
margin: 0 ${pxToRem(24)};
`;
export const ContentWrapper = styled.div`
display: flex;
align-items: center;
`;
export const Title = styled(Link)`
font-family: 'Ubuntu';
font-weight: bold;
font-size: ${pxToRem(28)};
color: ${({ theme }): string => theme.main};
text-decoration: none;
box-shadow: none;
`;
export const Links = styled(Link)`
font-family: 'Gothic A1';
color: ${({ theme }): string => theme.mainFont};
text-decoration: none;
box-shadow: none;
margin-right: 2rem;
`;
// header.tsx
import React, { ReactElement, useEffect, useState, useRef } from 'react';
import { useWindowScroll } from 'react-use';
import ThemeSwitchComponent from 'components/themeSwitch';
import { Header, Inner, Title, ContentWrapper, Links } from './header.style';
interface HeaderProps {
title: string;
checked: boolean;
setChecked: React.Dispatch<React.SetStateAction<boolean>>;
}
export default function HeaderComponent({
title,
checked,
setChecked,
}: HeaderProps): ReactElement {
// const [visibility, setVisibility] = useState<boolean>(false);
const visibility = useRef<boolean>(false);
const setVisibility = (bool: boolean): void => {
visibility.current = bool;
};
const [memoedY, setMemoedY] = useState<number>(0);
const { y } = useWindowScroll();
useEffect(() => {
setMemoedY(y);
console.log(`header: ${visibility}`);
if (y < memoedY || y === window.innerHeight) {
setVisibility(true);
} else {
setVisibility(false);
}
}, [y]);
return (
<Header scrolled={!!memoedY} visibility={visibility.current}>
<Inner>
<Title to='/'>{title}</Title>
<ContentWrapper>
<Links to='/about'>About</Links>
<Links to='/life'>Life</Links>
<ThemeSwitchComponent checked={checked} setChecked={setChecked} />
</ContentWrapper>
</Inner>
</Header>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment