banner



How To Put An Interactive Animation On A Web Page

How to Add Interactive Animations and Page Transitions to a Next.js Web App with Framer Motion

The web is vast and it'south total of static websites and apps. Simply merely because those apps are static, it doesn't hateful they have to exist tedious.

How can we use Framer Movement to add some animations to our web apps and provide a more than interactive experience?

  • What is Framer Move?
  • What are we going to build?
  • Stride 0: Installing Framer Motility in your Adjacent.js app
  • Step i: Animative the page title with Framer Motion in a Next.js app
  • Step 2: Adding animated hover effects with Framer Motion to elements in a Adjacent.js app
  • Stride 3: Adding page transitions with Framer Motion to a Side by side.js app
  • Stride 4: Using Framer Motion keyframes for advanced animations
  • Bonus Step: Getting a niggling weird with animations in our Adjacent.js Rick and Morty app

What is Framer Motility?

Framer Motion is an API that comes straight from the Framer API. It provides ready-to-become animations and gesture controls that makes it easy to create dynamic furnishings.

What is Framer? Framer itself is a UI prototyping tool that allows y'all to create interactive interfaces with animations that you tin hand off to your squad, while the Framer API is a Javascript library that lets you do that with code.

The Movement API stems from that work, but is conveniently bachelor as a separate package that we tin can use for animation command.

What are we going to build?

We're going to use the concepts of Framer Motion to add interaction and page transition furnishings to our app.

framer-motion-nextjs-animation-demo
Blitheness demo using Framer Motion

We'll showtime off with some bones animations that happen when the page load, learn how to trigger them on hover, and build out a wrapper that allows us to gracefully transition our pages in Next.js.

Before getting started

This is the second part of series of articles walking through building a Rick and Morty wiki. The showtime part focuses on requesting the data from the Rick and Morty API and creating dynamic pages.

How to Create a Dynamic Rick and Morty Wiki Web App with Adjacent.js

While you can follow forth without walking through the first one, it might exist helpful to have a identify to start from. Otherwise, you should be able to follow along almost of this with whatever React app.

Step 0: Installing Framer Motion in your Next.js app

Since we're going to utilize Framer Movement to provide our blitheness features, the showtime thing we desire to practice is install it!

One time y'all have the app running locally, you tin can install it with:

                yarn add together framer-motion # or npm install framer-motion                              

And at this point you tin can start back up your evolution server and nosotros'll be ready to go!

rick-and-morty-wiki-nextjs
Starting indicate - Rick and Morty wiki app in Side by side.js

Follow along with the commit!

Footstep 1: Animating the folio title with Framer Motion in a Next.js app

To get started, we're going to animate the page championship in our wiki app. Particularly, nosotros're going to configure Framer Move to brand the title fade in and grow when the folio first loads.

First things kickoff, we need to import Movement into our app.

Start off by calculation the following import argument to the height of pages/index.js:

                import { motion } from 'framer-movement';                              

And now that nosotros're ready to employ move, we can get started by wrapping out <h1> championship with a motion component:

                <movement.div>   <h1 className="title">     Wubba Lubba Dub Dub!   </h1> </motion.div>                              

Wrapping our element is what's going to allow the states to hook into the Motion API.

If nosotros reload our page though, it won't exist doing annihilation still. That's because we haven't even so configured our animation, so let's do that!

When using the Movement API with our <motion.10> component, we have two basic concepts we need to employ:

  • Animation lifecycle
  • Variants

Each of the animation lifecycle props such every bit initial and animate allow united states to define our animation's name as a variant.

Our variants prop is where nosotros configure those animations by defining variant names along with the animation nosotros'd similar them to perform.

So to start, let'southward add together 2 lifecycle definitions to our championship component by adding two lifecycle props:

                <motility.div initial="hidden" animate="visible">   <h1 className="title">     Wubba Lubba Dub Dub!   </h1> </move.div>                              

At present, nosotros want to ascertain those:

                <motion.div initial="hidden" animate="visible" variants={{   hidden: {},   visible: {}, }}>   <h1 className="championship">     Wubba Lubba Dub Dub!   </h1> </motion.div>                              

We're defining ii variants — subconscious and visible — which we so reference in the initial and animate lifecycle props.

Now again, reloading the page, it still won't do anything since nosotros still haven't defined the animations themselves, so let's do that:

                <motion.div initial="hidden" animate="visible" variants={{   hidden: {     scale: .8,     opacity: 0   },   visible: {     scale: one,     opacity: ane,     transition: {       delay: .4     }   }, }}>   <h1 className="title">     Wubba Lubba Dub Dub!   </h1> </motion.div>                              

Here'south what'southward going on:

  • Nosotros accept ii different lifecycles, an initial and an animate. The initial is what "initially" loads when the page loads where animate is what happens after the folio loads
  • In our initial state, we're setting the element to be slightly scaled down with a 0 opacity
  • When the page loads and triggers our blitheness, we set the calibration dorsum to 1 and the opacity back to 1
  • We're also setting a filibuster on our transition then that it ways .4s before firing the animation. This is but to help let things load a tiny scrap earlier triggering

So in the above, what's actually happening is .4s afterwards the page loads, we're going to fade in the championship and brand it look like it'southward slightly growing.

And if we save that and reload the page, we can encounter our title's issue!

animated-header-framer-motion
Blithe championship in Adjacent.js app with Framer Motion

Follow along with the commit

Pace 2: Calculation animated hover effects with Framer Motion to elements in a Next.js app

At present that we have a basic understanding of how to add animations when the page loads, let's starting calculation some interaction.

We're going to add some hover effects to each character card. That way, when your cursor moves over one of the cards, we'll trigger our animation.

First, inside of our unordered list grid <ul className="grid">, permit'south update the list element <li> to be a <motion.li> element:

                <motility.li key={id} className="card">   ... </motion.li>                              

If you lot save and reload the page, you'll notice that we really have an upshot.

rick-and-morty-wiki-missing-styles
App with missing styles for graphic symbol cards

Because of the integration betwixt movement and the Adjacent.js CSS integration, our app is getting tripped up on the course proper noun.

While this isn't fixing it at it's "core", we can fix this for our demo past removing the jsx prop from our top <style> block where inside, we have our .bill of fare definition.

Change:

                <style jsx>{`                              

To:

                <manner>{`                              

Now if we reload our folio, we're back to where we started off.

rick-and-morty-wiki-nextjs
App with correct styles

In order to add our hover effect, we're going to create a new prop on our <motion.li> component called whileHover and fill it with some base of operations styles:

                <motion.li central={id} className="card" whileHover={{   scale: 1.2,   transition: {     duration: .two   } }}>                              

Above, we're telling motion that when someone hovers over our element, we desire it to grow past scaling it to i.ii and nosotros want that animation to last .2s.

And if we reload the page, we can run across our animation!

rick-and-morty-wiki-hover-framer-motion
Hover outcome in Adjacent.js app using Framer Movement

If you lot await at the bottom of the outcome though, when the card grows, it's overlapping with the menu beneath it and looks a bit broken. We can ready that by applying some z-indexing and a background colour!

                <motility.li key={id} className="card" whileHover={{   position: 'relative',   zIndex: 1,   groundwork: 'white',   scale: 1.2,   transition: {     duration: .2   } }}>                              

And if we reload the folio again, nosotros tin can now meet that as our card grows, information technology appears on top of the carte du jour beneath information technology!

rick-and-morty-framer-motion-animation-fixed-layer
Fixing z-indexing and background on hover consequence

Follow along with the commit!

Step iii: Adding page transitions with Framer Motion to a Next.js app

Triggering some animations when the folio loads and hover furnishings is cool, but it'south a prissy touch when your app can provide graceful transitions betwixt pages. That can be role of what makes it experience more like a "web app" equally opposed to a static "website".

To do this, we'll need to configure our Side by side.js app with a wrapper effectually the root pages of the website. This will let us to hook into the navigation lifecycle and properly animate our pages.

Getting started, we demand to create a new file nether the pages directory chosen _app.js:

                // In pages/_app.js function App({ Component, pageProps }) {   return (     <Component {...pageProps} />   ) }  export default App;                              

While we don't necessarily take to sympathize the specifics of what'southward happening, we're basically creating a wrapper where we can patch in additional functionality.

With this new file, if you reload the page, you shouldn't see whatever changes yet.

Next, we're going to add our foundation that allows u.s.a. to set our page transitions.

Kickoff, permit's import movement at the summit of our page:

                import { motion } from 'framer-motion';                              

So, similar to our other animations, let's create a new <motility.div> component that wraps around our page.

                <motion.div initial="pageInitial" animate="pageAnimate" variants={{   pageInitial: {     opacity: 0   },   pageAnimate: {     opacity: ane   }, }}>   <Component {...pageProps} /> </motion.div>                              

Here, we're setting an initial land with an opacity of 0 and an animate land with an opacity of i, with the idea that it volition fade in.

Now if you hitting refresh, you'll notice that the page fades in. But if y'all click on one of the characters, when the character page loads, it doesn't fade in.

rick-and-morty-app-no-page-transitions
Irresolute page with no transition effect

The issue is, currently, the motion component doesn't understand information technology's a new route, so we need to force it to recognize that and update.

To do this, we're going to destructure the router argument in our App props:

                part App({ Component, pageProps, router }) {                              

And on our motion component, we're going to use it as a fundamental:

                <motility.div key={router.route} initial="pageInitial" animate="pageAnimate" variants={{                              

At present if we reload the page and navigate between our character folio and our homepage, you'll see it'south now fading in the content!

rick-and-morty-app-fade-page-transitions-framer-motion
Next.js fading page transition with Framer Move

Follow along with the commit!

Step iv: Using Framer Motion keyframes for advanced animations

Now that we've got the nuts of setting up animations in our app's lifecycle, nosotros can get more avant-garde by using keyframes.

The manner keyframes work, is when nosotros define an animation, we tin can set that animation to motion through a set of dissimilar values for our given property,  allowing us to build custom animations to our liking.

For case, say we want to brand an element on hover grow to 2x the size, brand it a piffling scrap smaller to 1.5x the size, then support to 2x the size all in ane animation sequence. We tin can practice that with keyframes!

The syntax for that would look like this:

                scale: [ane, ii, 1.five, two]                              

We're specifying our sequence using an array that says we want our element to outset off at it's normal size at 1x, then the next frame it will grow to 2x, then shrink a petty to 1.5x, so finally grow back to 2x.

To test this out, we're going to make some changes on our hover effect that we've already configured for our character cards.

In pages/alphabetize.js, update the whileHover property on our move listing elements to:

                <movement.li primal={id} className="card" whileHover={{   position: 'relative',   zIndex: 1,   background: 'white',   scale: [1, 1.4, 1.2],   rotate: [0, 10, -10, 0],   transition: {     duration: .2   } }}>                              

We're specifying 2 sets of keyframes, which are the following:

  • It's initial size is 1x and has 0 rotation (or no rotation)
  • Information technology then scales to 1.4x the size and rotates ten degrees
  • It and then scales dorsum downward to 1.2x the size and rotates the other way to -x degrees
  • At this point, the scale keyframes are consummate, so we wouldn't exist scaling anything more than, but we have ane last rotation, where we rotate back to our initial position of 0 (or no rotation)

And if we reload the folio and hover over our elements, we can see our effects in action!

rick-and-morty-hover-effect-framer-motion
Framer Motion hover consequence with rotation and scaling

Without keyframes, we can but do animation furnishings from a unmarried initial country to another single value. But with our keyframes, nosotros tin add more dynamic animations moving around to unlike values.

Follow along with the commit!

Bonus Step: Getting a little weird with animations in our Next.js Rick and Morty app

To add some other layer of fun to this, we can play with other backdrop that make our animations even more than dynamic.

To beginning, we're going to kick our hover effects up a notch.

On our pages/alphabetize.js file inside the whileHover prop of our <motion.li> card element, let's add together the following property:

                filter: [   'hue-rotate(0)',   'hue-rotate(360deg)',   'hue-rotate(45deg)',   'hue-rotate(0)' ],                              

Here, nosotros're setting up a new set of keyframes that will "rotate" the hue of the image based on the hue-rotate CSS function.

And if we save and reload our page, this gives us a overnice piddling color consequence.

rick-and-morty-hover-effect-weird-framer-motion
Changing colour of image on hover with Framer Motion and CSS filters

But that's too subtle enough for me — I want information technology a piffling more weird.

Allow's update our filter property to the following:

                filter: [   'hue-rotate(0) contrast(100%)',   'hue-rotate(360deg) contrast(200%)',   'hue-rotate(45deg) contrast(300%)',   'hue-rotate(0) contrast(100%)' ],                              

Now, not just does the color  change, nosotros use the contract CSS office to make the colors more farthermost giving us an fifty-fifty stranger effect.

rick-and-morty-framer-js-hover-effect-color
Irresolute dissimilarity and colors using CSS filters on hover with Framer Motility

Adjacent, we tin can exercise something a bit like with our page transitions!

To do this, we're going to use a new part of the Motion component lifecycle — the go out. To do this, we need to make use of Motion's AnimatePresence  component which allows u.s. to animate components when they're removed from the React tree.

So to kickoff, let's open pages/_app.js and import that component at the top:

                import { move, AnimatePresence } from 'framer-motion';                              

Side by side, we want to wrap our <motion.div> component with our new AnimatePresence component:

                <AnimatePresence>       <motion.div fundamental={router.road} initial="pageInitial" animate="pageAnimate" variants={{                              

With our component wrapped, nosotros can now prepare our new lifecycle prop leave along with its variant:

                <motion.div fundamental={router.route} initial="pageInitial" breathing="pageAnimate" exit="pageExit" variants={{   pageInitial: {     opacity: 0   },   pageAnimate: {     opacity: 1   },   pageExit: {     backgroundColor: 'white',     filter: `invert()`,     opacity: 0   } }}>                              

In the above, we're:

  • Configuring a pageExit variant
  • We set up out exit lifecycle prop to pageExit
  • Inside of our pageExit variant, we set up the background color to white and we add together a filter to invert the colors

Note: it'southward important to gear up the groundwork color to white, otherwise, the invert filter won't use to the background.

And if we save and reload the page, when we navigate to another element, nosotros get our effect!

rick-and-morty-app-page-transitions
Inverting colors on page transition with Framer Move

Follow along with the commit!

What else tin we do?

Add together some animations to stagger the search results

If you check out my original demo that I wrote this tutorial based on, I add together a feature that makes the results bladder in past shifting up slightly.

Nosotros can exercise that with the staggerChildren transition property and the setting the ten and y position properties on our listing elements.

https://github.com/colbyfayock/rick-and-morty-wiki/blob/master/pages/index.js#L11

Animate the buttons

Currently the buttons are just static. Add together some hover and click effects to the buttons like Load More at the bottom.

Add more weird effects

This is Rick and Morty after all, make it as weird as you can! Just withal make certain it's usable.

Follow me for more Javascript, UX, and other interesting things!

  • ? Follow Me On Twitter
  • ?️ Subscribe To My Youtube
  • ✉️ Sign Up For My Newsletter


Learn to code for gratuitous. freeCodeCamp's open up source curriculum has helped more than than 40,000 people get jobs as developers. Become started

Source: https://www.freecodecamp.org/news/how-to-add-interactive-animations-and-page-transitions-to-a-next-js-web-app-with-framer-motion/

Posted by: whitmorethisch.blogspot.com

0 Response to "How To Put An Interactive Animation On A Web Page"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel