CSS Transitions and Animations (Live Playground)
In this tutorial, you will learn how to use CSS transitions and animations to create smooth and engaging animations in your React applications.
CSS Transitions
CSS transitions enable you to create smooth animations when changing property values. To use transitions, define the transition
property in your CSS:
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: all 0.3s ease;
}
.box:hover {
width: 200px;
background-color: red;
}
import React from 'react';
import './Box.css';
const Box = () => {
return <div className="box"></div>;
};
export default Box;
In this example, when hovering over the .box
element, its width and background color change smoothly over 0.3 seconds.
CSS Animations
CSS animations allow you to create more complex animations by defining keyframes
:
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.spinner {
width: 100px;
height: 100px;
background-color: blue;
animation: spin 2s linear infinite;
}
import React from 'react';
import './Spinner.css';
const Spinner = () => {
return <div className="spinner"></div>;
};
export default Spinner;
In this example, we define a spin
animation that rotates the .spinner
element from 0 to 360 degrees. The animation is set to repeat infinitely every 2 seconds.
Combining CSS Transitions and Animations in React
You can combine CSS transitions and animations with React component states:
.fade {
opacity: 0;
transition: opacity 0.5s ease;
}
.fade.show {
opacity: 1;
}
import React, { useState } from 'react';
import './Fade.css';
const FadeToggle = () => {
const [show, setShow] = useState(false);
const toggle = () => {
setShow(!show);
};
return (
<div>
<button onClick={toggle}>Toggle</button>
<h1 className={`fade ${show ? 'show' : ''}`}>Hello, world!</h1>
</div>
);
};
export default FadeToggle;
In this example, clicking the "Toggle" button changes the .fade
element's opacity
, creating a smooth fade-in and fade-out effect.
Conclusion
Now you know how to use CSS transitions and animations in your React applications to create engaging and interactive user experiences.