7

I need to toggle on a css class after a component (or even the page) is completely rendered, so that relevant properties are animated on page load.

How do I go about doing this, preferably without jQuery?

If I toggle a component's class in componentDidMount, the animation doesn't actually happen.

eye_mew
  • 8,855
  • 7
  • 30
  • 50

2 Answers2

15

I didnt actually get the part where you say:

after a component (or even the page) is completely rendered, so that relevant properties are animated on page load.

When exactly do you want to animate the element ? If you specify the class name in render() function the component will be rendered with animation on page load.

If you want to control/toggle animation after first render, you can control the class name using component state like so:

var Hello = React.createClass({

    getInitialState: function(){
        return {
            condition:false
        }
    },

    handleClick :function(){
        this.setState( { condition : !this.state.condition } );
    },

    render: function() {
        return <div>
                <div className={this.state.condition ? "animated" :""}  >Hello {this.props.name}</div>
                <button type="button" onClick={this.handleClick}>Change Condition</button>

               </div>;
    }
});

React.render(<Hello name="World" />, document.body);

Here I changed the state in response to a button click. You may probably want to change this to some other event you like.

Here is a fiddle for the above code : http://jsfiddle.net/f0j4kt0L/

nilgun
  • 10,460
  • 4
  • 46
  • 57
  • 2
    So what I want to do is load the animation immediately after the page is loaded. I've tried exactly what you've suggested, but instead changing the `this.state.condition` in the componentDidMount method. The css class is applied immediately in that case, with no transition. – eye_mew Nov 13 '14 at 22:27
  • 1
    What happens when you change this line: '
    Hello {this.props.name}
    ' ? Doesn't it just work on page load: http://jsfiddle.net/3fmfous3/ ?
    – nilgun Nov 14 '14 at 06:48
  • 1
    this was a super helpful demonstration. really clarified it for me. – Jake Jun 21 '16 at 09:19
1

You can do it using toggle class as well.

var node = ReactDOM.findDOMNode(this.refs.el);
node.classList.toggle('menu-open');
rajesh_kw
  • 1,572
  • 16
  • 14