Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to React Component after a certain amount of time

Tags:

css

reactjs

I have a react component:

React.createComponent({

  render: function () {

    return (<div className="some-component"></div>);

  }
});

Some seconds after it renders, I want it to add a class from within the component. The class is for the purposes of revealing the component with an animation. I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction, so I'm loathed to initiate it from outside of the component via a change of store/state.

How would I do this in simple terms? Something like:

{setTimeout(function () {

  this.addClass('show'); //pseudo code

}, 1000)}

Obviously I could use jQuery, but that feels anti-React, and prone to side-effects.

like image 981
shennan Avatar asked Jan 06 '23 00:01

shennan


1 Answers

I don't regard it as a real change of state, as it has no affect on the application other than to give the component an animated introduction

A change of state in the component seems the natural and proper solution for this scenario. A change in a component state triggers a re-render, which is exactly what you need here. Consider that we're talking about the state of your component, not of your application here.

In React, you don't deal with the DOM directly (e.g. by using jQuery), instead your component state should "drive" what's rendered, so you let React "react" to changes in state/props and update the DOM for you to reflect the current state:

React.createComponent({

  componentDidMount () {
    this.timeoutId = setTimeout(function () {
        this.setState({show: true});
    }.bind(this), 1000);
  } 

  componentWillUnmount () {
    if (this.timeoutId) {
        clearTimeout(this.timeoutId);
    }
  }

  render: function () {

    return (<div className={this.state.show ? 'show' : null}></div>);

  }
});

When using setTimeout in React you need to be careful and make sure to cancel the timeout when the component gets unmounted, otherwise your timeout callback function will run anyway if the timeout is still pending and your component gets removed.

If you need to perform an initial mount animation or more complicated animations, consider using ReactCssTransitionGroup, which handles timeouts and other things for you out of the box: https://facebook.github.io/react/docs/animation.html

like image 151
fabio.sussetto Avatar answered Jan 08 '23 00:01

fabio.sussetto