React - animation example with CSS transition property

3 points
Created by:

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>

const root = document.querySelector('#root');
ReactDOM.render(<MyComponent />, root );

If the duration is not specified, the transition will have no effect, because the default value is 0.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.


React - animation with transition property
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂