Skip to main content

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:

CSS
.box {
width: 100px;
height: 100px;
background-color: blue;
transition: all 0.3s ease;
}

.box:hover {
width: 200px;
background-color: red;
}
JavaScript
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.

Live Playground, Try it Yourself

CSS Animations

CSS animations allow you to create more complex animations by defining keyframes:

CSS
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

.spinner {
width: 100px;
height: 100px;
background-color: blue;
animation: spin 2s linear infinite;
}
JavaScript
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.

Live Playground, Try it Yourself

Combining CSS Transitions and Animations in React

You can combine CSS transitions and animations with React component states:

CSS
.fade {
opacity: 0;
transition: opacity 0.5s ease;
}

.fade.show {
opacity: 1;
}
JavaScript
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.

Live Playground, Try it Yourself

Conclusion

Now you know how to use CSS transitions and animations in your React applications to create engaging and interactive user experiences.