Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Toggle class for css transition

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.

like image 542
eye_mew Avatar asked Nov 13 '14 13:11

eye_mew


2 Answers

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/

like image 53
nilgun Avatar answered Nov 18 '22 22:11

nilgun


You can do it using toggle class as well.

var node = ReactDOM.findDOMNode(this.refs.el);
node.classList.toggle('menu-open');
like image 43
rajesh_kw Avatar answered Nov 18 '22 23:11

rajesh_kw