Author avatar

Vivek Kumar

Toggling Class for CSS Transition in ReactJS

Vivek Kumar

  • Jun 20, 2019
  • 6 Min read
  • 39 Views
  • Jun 20, 2019
  • 6 Min read
  • 39 Views
Web Development
React

Introduction

In the world of animation, there are certain measures that seem like a complication which are, in reality, not a challenging task at all. One such case that usually generates a problem for the animators is the process to toggle the class fora CSS transition in ReactJS. In this guide, you will learn how to toggle class for CSS transitions in ReactJS. Our main objective is to find a precise and trustworthy solution which is easy to learn and implement.

Overview

Let us take, for example, a case where you are required to toggle a specific CSS class that is subsequent to an element (or the whole page) which is fully rendered. Here, all the relevant properties are to be animated on the page load. Now, we are going to toggle class in the absence of jQuery. If you toggle an element’s class in componentDidMount, it is the animation that won’t actually happen.

Before proceeding further, and in order to make the whole process seamless, there are certain questions that you need to answer in advance. For instance, at which phase precisely would you like to animate the component? It is, basically, necessary to decide this in advance because, during the coding, you are required to specify the exact class name in the render() function; this will make it so that the component will be rendered with the animation upon the page loading.

The Correct Approach

If you would like to avail toggle/control animation subsequently after the first render and to have control over the class name using the component state, you should follow the given code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
javascript

If you look at the code highlighted above then you will find that the changes have been accepted in the state, in response to the button click. Now, when you work with the application, it is totally up to you whether you might want to change it to some sort of other event or not.

Here's the complete code for toggling a button:

HTML

1
2
<h2 > React - toggle class (ES6) </ h2>
<div id="app"></div>
html

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
body {
  text-align: center;
  font-family: 'Roboto', sans-serif;
}
h2 {
  margin: 50px 0 10px;
}
.link {
  display: inline-block;
  margin-bottom: 50px;
}
.button {
  display: inline-block;
    font-size: 18px;
    color: #2f70e1;
    padding: 10px 30px; 
  margin-right: 10px;
  margin-bottom: 30px;
    box-shadow: 0px 1px 3px 0px rgba(0, 0, 0, .3);
  cursor: pointer;
  -webkit-user-select: none; /* Chrome/Safari */        
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* IE10+ */
}
.button-small {
  padding: 5px 10px;  
  font-size: 12px;
}
.toggled {
    background-color: #2f70e1;
    color: #fff;
}
button {
  margin-top: 80px;
}
css

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Here, the button has parent and child components. You can even keep it
// simple and use just one component for the button, but if you are learning React
// it's better for you to see how parent-child communication works in this simple example.
// In a real-life project, do not use 'div' for a button - think about accessibility

class ButtonParent extends React.Component {
  constructor(props) {    
    super(props)
    this.state = {
      condition: false
    }
    this.handleClick = this.handleClick.bind(this)
  }
  handleClick() {
    this.setState({
      condition: !this.state.condition
    })
  }
  render() {
    return (
      <ButtonChild        
        className={ this.state.condition ? "button toggled" : "button" }
        toggleClassName={ this.handleClick }
      >
        Toggle me!
      </ ButtonChild>
    )
  }
}

class ButtonChild extends React.Component {
  render() {
    return (
      <div
        className={ this.props.className }
        onClick={ this.props.toggleClassName }
      >
        { this.props.children }
      </ div>
    )    
  }
}

ReactDOM.render(<ButtonParent />, document.getElementById('app'))
javascript

This results in a button with the text “Toggle me!” which gets highlighted and unhighlighted when clicked one after the other.

To immediately load an animation after the page is loaded, you can go with the above code; just change the this.state.condition in the componentDidMount method. As a programmer, what you need to take into account is the compatibility with the browser. Do make sure to run some compatibility tests in advance to verify that everything is running correctly at each step of the transition. I recommended this due to the fact that, if there is a compatibility issue with the browser, there are chances that the CSS class is implemented straightaway without transition actually taking place.

As an alternative way, in the CSS class, you can also apply toggle class in the following manner:

1
2
var node = ReactDOM.findDOMNode(this.refs.el);
node.classList.toggle('menu-open');
javascript

Conclusion

Now, the method that we used to toggle class for a CSS transition in React JS is assured to render the positive results. Basically, this is because we have set the state ideally and run the tests to ensure compatibility. In ReactJS, we have set the function in the initial state (as you can see above) so that we can state the classname and change the condition with a single button click.

Reference

While writing this guide, the following resources have been referred to:

0