Go Pro Sign Up Login

Buy Now and unlock this series

$

39

.99

$

32

.99

yours forever

Become a Pro and unlock everything

$

24

.99

per month

Animated Page Transitions With The Web Animations API

This video is about #13 Animated Page Transitions With The Web Animations API - Pro Gatsby

Downloads

Become a pro to download code and videos

Comments

Martin Coutts

over 1 year ago [edited]

Just as an excercise I tried only using react hooks as I now hate writing classes. For anyone else who wants to do this here is the code.

The animation has some weird behaviour but I am not sure if this is due to not using the same image code as Scott's video due to it being updated.

Anyway happy coding.

import { Link } from "gatsby"
import PropTypes from "prop-types"
import React, { useEffect, useRef } from "react"
import styled from "styled-components"
import Img from "gatsby-image"

import logo from "../images/logo.svg"

const HeaderWrapper = styled.div`
  background: #524763;
  margin-bottom: 1.45rem;
  overflow: hidden;
  position: relative;
  height: ${({ isHome }) => (isHome ? "70vh" : "20vh")};
  h1 {
    img {
      height: 80px;
    }
  }
`

const HeaderContainer = styled.div`
  margin: 0 auto;
  max-width: 960px;
  padding: 1.45rem 1.0875rem;
  position: relative;
  z-index: 2;
`

const Header = ({ data, location }) => {
  const wrapper = useRef(null)

  useEffect(() => {
    if (location.pathname === "/") {
      wrapper.current.animate([{ height: "20vh" }, { height: "70vh" }], {
        duration: 300,
        fill: "forwards",
        easing: "cubic-bezier(0.86, 0, 0.07, 1)",
        iterations: 1,
      })
    } else {
      wrapper.current.animate([{ height: "70vh" }, { height: "20vh" }], {
        duration: 300,
        fill: "forwards",
        easing: "cubic-bezier(0.86, 0, 0.07, 1)",
        iterations: 1,
      })
    }
  }, [location.pathname])

  return (
    <HeaderWrapper ref={wrapper} isHome={location.pathname === "/"}>
      <HeaderContainer>
        <h1 style={{ margin: 0 }}>
          <Link
            to="/"
            style={{
              color: `white`,
              textDecoration: `none`,
            }}
          >
            <img src={logo} alt="Level Up Logo" />
          </Link>
        </h1>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/about">About</Link>
            </li>
          </ul>
        </nav>
      </HeaderContainer>
      <Img
        style={{
          position: "absolute",
          left: 0,
          top: 0,
          width: "100%",
          height: "100%",
        }}
        sizes={data.background.childImageSharp.fluid}
      />
    </HeaderWrapper>
  )
}

Header.propTypes = {
  siteTitle: PropTypes.string,
}

Header.defaultProps = {
  siteTitle: ``,
}

export default Header

Want to join the conversation?

Become a Pro member today!