Making an animated header with Framer Motion
Rafael Sant'Ana
Posted on September 21, 2020
Hi! Recently I've watched a video about basics of Framer Motion - A ReactJS library made in order to help to make animations - and I wanted to share a little bit of what I've learnt.
We will create a simple header component, and it will work just like the below one (Pay attention to the scrollbar and the header):
In order to start, You need to create a react app and install 'framer-motion' library
# Creating a react app
npx create-react-app framer-header / yarn create react-app framer-header
# Installing with NPM and with Yarn:
npm install framer-motion / yarn add framer-motion
So, even though I'm still studying it, I've learnt a bit about animations throughout the page scroll, doing this would usually be kinda difficult but happily We have Framer motion + React hooks !
In order to make a simple animation that makes the header disapear, we can start by creating a basic Header component in 'src/components/Header.js':
Okay, but... what are 'motion', 'useViewportScroll' and 'useTransform'?
Motion is kind of a component that You use for styling, just like 'animated' from React Spring.
useViewportScroll is a hook that returns how many % of the page has been scrolled in decimal numbers, in this case, we want to know how many % of the Y axis has been scrolled
useTransform is the hook that allows us to make some of animations, in this case, it is what will make our header leave the screen. It works at the following way: When the value of the first parameter is in the range of the second parameter, it will return a number depending on the third parameter
Confusing? Maybe, but let me show you two examples:
const scaleY = useTransform(
2,
[1, 4],
['0%', '100%'],
);
scaleY would be ' 50% ' because 2 is in the exact middle between 1 and 4, but if the first parameter were ' 4 ', scaleY would be 100%
const { scrollYProgress } = useViewportScroll();
const headerY = useTransform(
scrollYProgress,
[0, 0.2, 0.3],
['0%', '0%', '-100%'],
);
When 0% of the page has been scrolled, headerY will be ' 0% ',
When 20% of the page has been scrolled, headerY will be ' 0% ',
When 25% of the page has been scrolled, headerY will be ' -50% ',
When 30% of the page has been scrolled, headerY will be '-100% ',
Now, so that we can see this component and the scrollbar, lets make some changes in 'App.js', it will be just like this one:
You can check the code out in the following link: https://codesandbox.io/s/purple-lake-k33ly
That's it guys, see you!
Posted on September 21, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.