How do I use Framer Motion with React, TypeScript and styled components? -pagepro (2023)

As you already know, Framer Motion is a really powerful animation library used by manyRespond to application development companies.

Now it's time to start doing that.

Here are some basics.

Introduction to Framer Motion

To start using Framer Motion for React, you need to install the right package:

npm

npm install framer-motion – salvar

Hilo

Add framer thread movement

The next step is to importbehavedfrom toreaction bagin the file we want to use:

import {motion} from 'framer-motion';

And now the fun begins!

We can animate any HTML or SVG element. We can use styling components, css modules, scss, css or whatever we want to add styles. There are two ways to create lofted components:

1. If you use class names:

import, move it to the file you want to use it in, like this:

import {motion} from 'framer-motion';

Add the HTML element after moving. and enclose it in angle brackets, just like a normal HTML tag or component, add the required class name:

<motion.div className="box" />

As a result, a div with the class name .box is created. You can use it to add styles to this element. Animation properties are added via variant and animation settings, so you don't have to deal with them in CSS.

2. If you use StyledComponents:

The first step is the same as 1.a, but you also need to import with style to use style components:

import {motion} from 'framer-motion'; import 'stylized components' style;

Crie StyledComponent com move element como tag:

(Video) React Typescript and Styled-Components Tutorial

const BoxStyled = styled(motion.div)` display: flex;`;

Use it the same way as in 1.b. Don't add a class name this time:

return <BoxStyled />;

animate

To prepare the animation, we need to use theanimateProperty.

It needs to be added to the Motion component (in this case it will be BoxStyled).

To create a simple animation, we can pass some attributes directly to theanimatesupport like this:

return <BoxStyled animate={{ escala: 0.5 }} />;

It starts when the component renders on the page.

You might be wondering what happens to the animation transition.

Well, Motion creates an appropriate animation for a quick transition based on the types of values ​​being animated.

“For example, physical properties like x or scale are animated by a spring simulation. Whereas values ​​like opacity or color are animated with a tween.”

It can be passed as an attribute within the animated property or as a separate transition property.

If no transition is specified in Animate, Motion gets its settings from the transition property:

return ( <BoxStyled animate={{ scale: 0.5 }} transit={{ duration: 2 }} />);

And that is. You've created your first motion animation!

Want to use Framer Motion in your project?

(Video) Use Framer Motion with Styled Components

SCHEDULE A FREE CALL WITH OUR EXPERT.

variants

To create a more advanced animation that can adapt based on changes within a component, we need to prepare some variants: the animation states our component will be in, for example B. open and closed, visible and hidden, etc.

Let's do it step by step:

Step 1

Prepare the variant configuration object - you can name it whatever you like and then use that name inside the StyledComponent. Inside you must add animation.state namesas visible and hidden:

Constant variants = { visible: {}, hidden: {}};

step 2

After declaring your states, it's time to add some animation properties. In this example we wantShowjhidethe element, so these are the attributes we want to animate:

constant variants = { visible: { opacity: 1, transition: { duration: 3 } }, hidden: { opacity: 0 }};

stage 3

Add a variant setting as an attribute to the StyledComponent, as follows:

const BoxStyled = styled(motion.div).attrs(() => ({ inicial: "hidden", Varianten}))` display: flex;`;

You can set the start variant if you want your animation to start with it (not required).

Step 4

Set the desired animation variant on a component:

return <BoxStyled animate="visible" />;

You can also change the animation dynamically, for example when the state changes:

import * as React from "react";import { useState } from "react";import { BoxStyled } from "./styles";const Box: React.FC = () => { const [isVisible, setIsVisible] = useState< boolean>(false); return (<> <button type="button" onClick={() => setIsVisible(prevState => !prevState)} > Click here to make content visible </button> <BoxStyled animate={isVisible ? " visible" : " hidden"} > I'm visible! </BoxStyled> </> );};export default frame;

And voila! Next animation ready!

It should look like this:

What happens to the kids?!

Now that you've asked:

“When a motion component has children, changes to the variant flow through the component hierarchy. These variant changes flow until a child component sets its own animation property.”

(Video) Creating High-Quality React Components: Best Practices for Reusability

If you don't want the children to inherit the animation from their parents, you can add the inheritance prop and set it to false.

The animation of the children starts at the same time as the animation of the parents.

If we want the parent to orchestrate the execution of the child animations, we can use some additional transition supports that we have access to when using variants:

  • What if
  • delay children
  • staggering children
constant variants = { visible: { opacity: 1, transition: { if: "beforeChildren", staggerChildren: 0,3, } }, hidden: { opacity: 0, transition: { when: "afterChildren", } }};

Here is a live example:

There are many great properties you can use. You can find them all onDocumentation.

Become a better web developer

Get tips from our expert web developers once a month.

AnimatePresence

If you work on React projects, you know that sometimes we want to render a component or part of it and sometimes we don't or just don't.

This causes a small problem with animations because we can't add an effect to an element that just disappears.

Motion provides a component calledAnimatePresencethat helps us in such situations. It is very easy to use and offers some hooks that we can use on our children.

import { motion, AnimatePresence } de "framer-motion" export const MyComponent = ({ isVisible }) => ( <AnimatePresence> {isVisible && ( <StyledBox initial={{ opacity: 0 }} animate={{ opacity: 1 } } exit={{ opacid: 0 }} /> )} </AnimatePresence>)

In this example, our component will only render if the isVisible property is set to true.

To use this component correctly, we need to add an exit animation.

It is used when the component self-decomposes. AnimatePresence must always exist in the DOM.

(Video) Personal Portfolio using React ( framer-motion , Styled-components ) , React Hooks

events and gestures

As mentioned at the beginning, this library offers more advanced listeners and extends the basic set of event listeners provided by React. We can use:

  • float up- detect when a pointer passes or leaves a component
    • while hovering
    • onHoverStart(event, info)
    • onHoverEnd(event, info)
  • to knock- Detects when a pointer presses and releases the same component
    • while playing
    • onTap(event, info)
    • onTapStart(event, info)
    • onTapCancel(event, info)
  • pan- detects when a pointer presses on a component and moves more than 3 pixels
    • onPan(event, info)
    • onPanStart(evento, info)
    • onPanEnd(event, info)
  • drag- Follows the pan gesture rules, but applies the pointer movement to the x and/or y axis of the component
    • drag
    • towing restrictions
    • DragElastic
    • pull momentum
    • DragTransition
    • drag propagation
    • drag controls
    • onDrag(evento, info)
    • onDragStart(evento, info)
    • onDragEnd(event, data)
    • onDirectionLock(eje)

You can read more about them.on here.

There are many options for us. We can even add separate animations to elements at the start of the event, at the end of the event, and while the event is active. You can't do this with CSS alone.

Here is a live example with a very simple animation:

SVG

There is also the option to have fun with SVG files. We can animate all elements as usual. Motion offers some additional properties for routes:

  • route length
  • Pfadabstand
  • path offset

Everything can be set to a value between 0 and 1.

“A note about SVG filters.
While helper properties do not work on SVG filter components because these elements have no physical presence and therefore do not receive events. To respond to gestures, you need to inject react state into the component and attach listeners to the physical element.

So there are also some limitations. I've put together a very simple animation using SVG below.

It is created with pathLength.

And now this?

I think the movement gives us many opportunities and, in many cases, makes our lives easier.

Definitely worth learning.

You can start with the simple animations in this article and then build something of your own.

There are also many examples inFramer Movement DocumentationSide. You can be inspired by some of them.

Are you ready to increase development effectiveness?

Get the tips once a month. It's not garbage.

(Video) Page Transitions In React - React Router V6 and Framer Motion Tutorial

Videos

1. React Food/Restaurant Website - Styled Components and Framer Motion Tutorial - Part 1
(Chaoo Charles)
2. Animate ANYTHING in TWO Lines Of Code!?!???
(Theo - t3․gg)
3. Animations In React - Framer-Motion Tutorial
(PedroTech)
4. React Typescript And CSS Reusable 3D Link Button Component
(Full Stack Coder)
5. Next.js 13 with Framer-motion animation
(For Those Who Code)
6. React Portfolio Website with Styled Components and Framer Motion 🔥
(Kishan Sheth)

References

Top Articles
Latest Posts
Article information

Author: Cheryll Lueilwitz

Last Updated: 07/15/2023

Views: 5738

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Cheryll Lueilwitz

Birthday: 1997-12-23

Address: 4653 O'Kon Hill, Lake Juanstad, AR 65469

Phone: +494124489301

Job: Marketing Representative

Hobby: Reading, Ice skating, Foraging, BASE jumping, Hiking, Skateboarding, Kayaking

Introduction: My name is Cheryll Lueilwitz, I am a sparkling, clean, super, lucky, joyous, outstanding, lucky person who loves writing and wants to share my knowledge and understanding with you.