React page animation using react-spring
Start by scaffolding a project with the react create app command
npx create-react-app spring-animation
ce spring-animation
Then install react spring animation
npm i s react-spring
We will then import the useSpring hook and animated from react-spring
import { useSpring, animated } from "react-spring";
We want to animated the header div from 100% to 50% and the logo from 100% to 40%. Thus they will initially take their original size and shrink to half of that.Also with a delay of 1000ms.
In our App function we make use of the hook and difine the following
const contentWrapper = useSpring({
delay: 1000,
from: { width: "100%" },
to: { width: "50%" },
});
const logoWrapper = useSpring({
delay: 1000,
from: { width: "100%" },
to: { width: "40%" },
});
To make use of this in our render app we need to pass them as styles to the element and append the elements with animated.
return (
<div>
<animated.div className="App" style={contentWrapper}>
<header className="App-header">
<animated.img
style={logoWrapper}
src={logo}
className="App-logo"
alt="logo"
/>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</animated.div>
</div>
);
full code
import React from "react";
import PropTypes from "prop-types";
import { useSpring, animated } from "react-spring";
import logo from "./logo.svg";
import "./App.css";
const App = () => {
const contentWrapper = useSpring({
delay: 1000,
from: { width: "100%" },
to: { width: "50%" },
});
const logoWrapper = useSpring({
delay: 1000,
from: { width: "100%" },
to: { width: "40%" },
});
console.log(contentWrapper);
return (
<div>
<animated.div className="App" style={contentWrapper}>
<header className="App-header">
<animated.img
style={logoWrapper}
src={logo}
className="App-logo"
alt="logo"
/>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</animated.div>
</div>
);
};
export default App;
All done! you can test your functionality b starting the application