Approach
- Use the
useState
hook to manage the hover state of the card. This state will track whether the card is being hovered over or not. - Utilize the
onMouseEnter
andonMouseLeave
events on the card container to toggle the hover state based on user interaction. - Import
Motion
andspring
from ‘react-motion’ to create smooth animations. Define animation logic usingspring
for transitioning the card’s rotation based on the hover state. - In the JSX, apply the
transform
property to the card based on the animatedrotateY
value provided by React Motion. - Ensure that your CSS styles support the flip animation by setting up transitions, perspective, and backface visibility appropriately.
Eample: This example shows the use of motion component.
/* App.css */
.app {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.title {
margin-bottom: 20px;
font-family: Arial, sans-serif;
}
.card-container {
perspective: 1000px;
}
.card {
width: 200px;
height: 300px;
position: relative;
transform-style: preserve-3d;
transition: transform 0.5s ease;
}
.front,
.back {
position: absolute;
width: 100%;
height: 100%;
backface-visibility: hidden;
display: flex;
justify-content: center;
align-items: center;
font-size: 24px;
color: white;
border-radius: 8px;
}
.front {
background-color: #3498db;
}
.back {
background-color: #2ecc71;
transform: rotateY(180deg);
}
//App.js
import React, { useState } from 'react';
import { Motion, spring } from 'react-motion';
import './App.css';
const App = () => {
const [isHovered, setIsHovered] = useState(false);
return (
<div className="app">
<h1 className="title">
Card Flip Animation
</h1>
<div
className="card-container"
onMouseEnter={
() => setIsHovered(true)}
onMouseLeave={
() => setIsHovered(false)}>
<Motion
defaultStyle={{ rotateY: 0 }}
style={{
rotateY: spring(isHovered ? 180 : 0,
{ stiffness: 120, damping: 10 }) }}>
{({ rotateY }) => (
<div
className="card"
style={{
transform: `rotateY(${rotateY}deg)`,
}}>
<div className="front">Front</div>
<div className="back">Back</div>
</div>
)}
</Motion>
</div>
</div>
);
};
export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Intorduction to React Motion
Animation plays a vital role in modern web development, enhancing user experience and adding a layer of interactivity to web interfaces. React Motion is a popular animation library specifically designed for React applications.
This article will explore React Motion in detail, covering its key features, benefits, usage, and examples.
Table of Content
- What is React Motion?
- Key Features of React Motion
- Benefits of Using React Motion
- Step-by-step Installing React project & React-motion
- The
component - Approach
Contact Us