Scroll Element

A Framer Motion animation component that allows for directional animations, including movement from left, right, or bottom.

Installation

npm install framer-motion
scroll-element.tsx
1
import { cn } from '@/lib/utils';
2
import {
3
motion,
4
HTMLMotionProps,
5
SVGMotionProps,
6
ForwardRefComponent,
7
Variant,
8
useAnimation,
9
} from 'framer-motion';
10
import React from 'react';
11
type Direction = 'up' | 'down' | 'left' | 'right';
12
13
const generateVariants = (
14
direction: Direction
15
): { hidden: Variant; visible: Variant } => {
16
const axis = direction === 'left' || direction === 'right' ? 'x' : 'y';
17
const value = direction === 'right' || direction === 'down' ? 100 : -100;
18
19
return {
20
hidden: { filter: 'blur(10px)', opacity: 0, [axis]: value },
21
visible: {
22
filter: 'blur(0px)',
23
opacity: 1,
24
[axis]: 0,
25
transition: {
26
duration: 0.5,
27
ease: 'easeOut',
28
},
29
},
30
};
31
};
32
33
const defaultViewport = { amount: 0.3, margin: '0px 0px -200px 0px' };
34
type MotionComponentProps = HTMLMotionProps<any> & SVGMotionProps<any>;
35
36
interface ScrollElementProps extends Omit<MotionComponentProps, 'children'> {
37
children: React.ReactNode;
38
className?: string;
39
variants?: {
40
hidden?: any;
41
visible?: any;
42
};
43
viewport?: {
44
amount?: number;
45
margin?: string;
46
once?: boolean;
47
};
48
delay?: number;
49
direction?: Direction;
50
}
51
52
function ScrollElement({
53
children,
54
className,
55
variants,
56
viewport = defaultViewport,
57
delay = 0, // Default delay is 0
58
direction = 'down',
59
...rest
60
}: ScrollElementProps) {
61
const baseVariants = variants || generateVariants(direction);
62
const modifiedVariants = {
63
hidden: baseVariants.hidden,
64
visible: {
65
...baseVariants.visible,
66
transition: {
67
...baseVariants.visible.transition,
68
delay, // Apply custom delay here
69
},
70
},
71
};
72
73
return (
74
<motion.div
75
whileInView='visible'
76
initial='hidden'
77
variants={modifiedVariants}
78
viewport={viewport}
79
className={cn(className)}
80
{...rest}
81
>
82
{children}
83
</motion.div>
84
);
85
}
86
export default ScrollElement;

Props

PropTypeDefaultDescription
childrenReact.ReactNodeThe content to be rendered within the scroll element.
classNamestringOptional CSS class for styling the scroll element.
variantsobjectAnimation variants for different scroll states (hidden/visible).
viewportobject{ amount: 0.5, margin: '0px', once: true }Settings for when the element is considered in view.
delaynumber0Delay before the animation starts, in milliseconds.
directionDirection'down'The scroll direction for the animation (e.g., 'down', 'up').

Example

Repeat Animation

Text Animation