Create a Transitioning Header Using React Hooks (like Medium)

Matt Holland
mattholland
Published in
4 min readAug 26, 2019

--

Article Summary: Use React’s useEffect and useState hooks to build a header that hides/shows on scroll.

The completed app that you will build

One small note on setup: I recommend that you use thecreate-react-app boilerplate to scaffold this project. The article assumes that you already have a project structure to work with and does not cover configuration instructions. I also recommend that you read Dan Abramov’s hooks article as a good introduction to why the React team created hooks.

General HTML Structure

Our simple page layout will consist of a <Header /> component and a <Body /> component. The Header will have fixed positioning so that it remains at the top of the viewport, and so that it’s hide/show transitions do not affect the Body component’s positioning:

Build the Header markup

The Header will consist of a main wrapper with typical nav content. The most important part of this markup will be our className variables which will trigger the hide/show transitions (via transform: translateY();) and add the box-shadow. Let’s create the basic markup and incorporate our future style variables:

Add hooks for managing hide/show styles

Now we need to start implementing React hooks (are you hooked yet?!) to manage the className variables from above. We will set up two useState hooks. One will be responsible for updating hiddenStyle, and the other will be responsible for updating shadowStyle.

I like to follow best practices for my hook variable names. The first variable name should always be declarative; an outsider should be able to infer what the variable does from just reading it. The section variable…

--

--

Matt Holland
mattholland

Software engineer based in Austin, TX, fueled by an endless stream of digital curiosity.