Approach to implement Animation with react-motion.
Step 1: Create a react project.
npx create-react-app <-project-name->
Step 2: Navigate to project directory.
cd <-project-name->
Step 3: install react-motion and update dependencies.
npm install react-motion
Create a Box Component, and import that in app.js
Example: To demonstrate creating a simple animation that moves a box from left to right using the react -motion.
// src/Box.js
import React from 'react';
import { Motion, spring } from 'react-motion';
const Box = () => {
return (
<Motion defaultStyle={{ x: 0 }} style={{ x: spring(200) }}>
{style => (
<div style={{
transform: `translateX(${style.x}px)`,
width: '100px',
height: '100px',
backgroundColor: 'blue'
}}>
</div>
)}
</Motion>
);
};
export default Box;
// src/App.js
import React from 'react';
import Box from './Box';
function App() {
return (
<div className="App">
<h1>React-Motion Example</h1>
<Box />
</div>
);
}
export default App;
Output:
Example: To demonstrate creating a staggeredBoxes component using the react motion
// src/StaggeredBoxes.js
import React from 'react';
import { StaggeredMotion, spring } from 'react-motion';
const StaggeredBoxes = () => {
const defaultStyles = [{ x: 0 }, { x: 0 }, { x: 0 }];
const finalStyles = prevStyles =>
prevStyles.map((_, i) => {
return i === 0
? { x: spring(200) }
: { x: spring(prevStyles[i - 1].x) };
});
return (
<StaggeredMotion defaultStyles={defaultStyles}
styles={finalStyles}>
{interpolatedStyles =>
<div>
{interpolatedStyles
.map((style, i) =>
<div key={i} style={{
transform: `translateX(${style.x}px)`,
width: '100px',
height: '100px',
backgroundColor: 'blue',
margin: '10px'
}}>
</div>
)}
</div>
}
</StaggeredMotion>
);
};
export default StaggeredBoxes;
// src/App.js
import React from 'react';
import StaggeredBoxes from './StaggeredBoxes';
function App() {
return (
<div className="App">
<h1>React-Motion Example</h1>
<StaggeredBoxes />
</div>
);
}
export default App;
Output:
Animating with react-motion
React-Motion is a popular animation library for React that allows developers to create smooth, natural animations in their applications. It leverages physics-based animation principles to create more realistic motion effects compared to traditional CSS animations or JavaScript based animation libraries. React-Motion provides an easy-to-use API for defining animations, making it ideal for adding dynamic interactions to your React components.