EN
React - animation example with CSS transition property
3 points
In this article, we would like to show you how to use transition
style property in React.
Below example presents two style objects: myComponentNormnal
and myComponentBig
with transition
value set to '0.5s'
. It means our component will change it's property values smoothly, over a given duration (0.5s
).
Runnable solution:
xxxxxxxxxx
1
// Note: Uncomment import lines during working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const myComponentNormal = {
6
width: '120px',
7
height: '120px',
8
background: 'goldenrod',
9
transition: '0.5s'
10
}
11
12
const myComponentBig = {
13
width: '200px',
14
height: '200px',
15
background: 'yellowgreen',
16
transition: '0.5s'
17
}
18
19
const MyComponent = () => {
20
const [bigSize, setBigSize] = React.useState(false);
21
const handleClick = () => setBigSize(!bigSize);
22
return (
23
<div style={{height: '220px'}}>
24
<div style={bigSize ? myComponentBig : myComponentNormal} >
25
<button onClick={handleClick}>Change size</button>
26
</div>
27
</div>
28
)
29
}
30
31
const root = document.querySelector('#root');
32
ReactDOM.render(<MyComponent />, root );
Note:
If the duration is not specified, the transition will have no effect, because the default value is0
.