const animate_boxes = () => {
inner_ref.current.style.transform = "scale(0)";
setTimeout(() => {
if (inner_ref && inner_ref.current) {
inner_ref.current.style.transform = "scale(1)";
}
}, 200);
};
useEffect(() => {
animate_boxes();
}, [trigger])
Currently, that is how I do it.
Is is this the standard/good practice way? If not, how can I re write the code above to simplify?
CodePudding user response:
There's an excellent hooks based animation library called react-spring, you can use it by itself or alongside a gesture library to create nice, physics based animations that look natural. It has a bit of a learning curve though, here's the library's website
CodePudding user response:
Another way you can animate is by utilizing the CSS transition attribute with react state and inline styles:
https://codesandbox.io/s/react-playground-forked-3t3p6?file=/Hello.js
import React, { useEffect, useState } from "react";
const blueSquare = {
width: "25px",
height: "25px",
backgroundColor: "blue",
transition: "opacity 0.5s, transform 3s",
margin: 20
};
const Hello = () => {
const [opacity, setOpacity] = useState(1);
const [transform, setTransform] = useState("translate(0,0) scale(1)");
useEffect(() => {
setTransform("translate(100px, 150px) scale(8)");
setTimeout(() => {
setTransform("translate(300px, 150px) scale(8)");
}, 3000);
}, []);
return (
<div>
<button
onClick={() => setOpacity((prevState) => (prevState === 1 ? 0 : 1))}
>
Animate Opacity
</button>
<div style={{ ...blueSquare, transform, opacity }} />
</div>
);
};
export default Hello;
But as Brandon mentioned if you want to do complex animations it'd most likely be easier looking into react-spring.