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:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const myComponentNormal = {
width: '120px',
height: '120px',
background: 'goldenrod',
transition: '0.5s'
}
const myComponentBig = {
width: '200px',
height: '200px',
background: 'yellowgreen',
transition: '0.5s'
}
const MyComponent = () => {
const [bigSize, setBigSize] = React.useState(false);
const handleClick = () => setBigSize(!bigSize);
return (
<div style={{height: '220px'}}>
<div style={bigSize ? myComponentBig : myComponentNormal} >
<button onClick={handleClick}>Change size</button>
</div>
</div>
)
}
const root = document.querySelector('#root');
ReactDOM.render(<MyComponent />, root );
Note:
If the duration is not specified, the transition will have no effect, because the default value is0
.