Author avatar

Vivek Kumar

ReactJS: CSS Transition Group

Vivek Kumar

  • Jun 6, 2019
  • 12 Min read
  • 988 Views
  • Jun 6, 2019
  • 12 Min read
  • 988 Views
Web Development
React

Introduction

When we talk about the application of the React Transition Group, there are several dilemmas that exist within the mind of a beginner. Many new coders compare the components and results with the animation library, such as React-Motion. Here, it is worth mentioning that there is no slightest resemblance between the two. React Transition Group does not accomplish the animation styles by itself. The group exposes the transition stages as well as manages the group elements and classes and manipulates the Document Object Model (DOM) in several expedient ways. It helps in the execution of real visual transition to a greater extent.

When we observe the components and function of React Transition Group then it can be seen underway.

Installation

1
2
3
4
5
# npm
npm install react-transition-group --save

# yarn
yarn add react-transition-group

Content Delivery Network (CDN)/ External

It is quite obvious that as React Transition Group is relatively small; the overhead of incorporating the library in user’s application is insignificant. Nevertheless, in the conditions where it might be helpful to avail advantage from an external content delivery network when bundling, the user can link the following content delivery network.

The following are the standard components of React Transition Group:

  1. Transition
  2. TransitionGroup
  3. CSS Transition

Animating Table Cells in React CSS Transition Group

Let us take an example over here. The user has to render, let’s say, about 100 rows with React, but the end result is expected to have the rows acting one by one. Is there an accurate way to perform this with the help of CSS React? The user can accomplish this with the help of the ReactCSSTransitionGroup package.

The render application applied by the user should be like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// ...

render: function() {
    var headerComponents = this.generateHeaders(),
        rowComponents = this.generateRows();

    return (
        <table>
            <thead>{headerComponents}</thead>
            <ReactCSSTransitionGroup
              transitionName="fade"
              transitionEnterTimeout={500}
              transitionLeaveTimeout={300}
              transitionAppearTimeout={500}
              transitionAppear={true}
              component="tbody"
            >
              {rowComponents}
            </ReactCSSTransitionGroup>
        </table>
    );
},

// ...
javascript

After that, one is required to define the CSS classes. In terms of a fade animation name, it can be like:

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
.fade-enter {
  opacity: 0.01;
}

.fade-enter.fade-enter-active {
  opacity: 1;
  transition: opacity 500ms ease-in;
}

.fade-leave {
  opacity: 1;
}

.fade-leave.fade-leave-active {
  opacity: 0.01;
  transition: opacity 300ms ease-in;
}

.fade-appear {
  opacity: 0.01;
}

.fade-appear.fade-appear-active {
  opacity: 1;
  transition: opacity .5s ease-in;
}
css

Animating the Element Height with React CSS Transition Group

It has been observed that while trying to animate the element height with the help of ReactCSSTransitionGroup, there are certain challenges that the users face. While doing the animation, the user will be unable to realize the exact element height. In the standard procedure, the user would try to hack the clientHeight, and scrollHeight while setting the componentDidMount and then try to set the node.style.height or, rather, inculcates the rules to the style-sheet.

The resulting animation appears fine, but when the element enters, there is a bit of flash that appears and the resulting scaling animation appears abnormal.

It basically happens because the application node.scrollHeight results in the occurrence of the rendering on a spontaneous basis. Now, the effort should be made by the user to acquire the same information in the process but introduce the CSS rules prior to the beginning of the animation.

Well, the good news is that it is feasible and could be accomplished by writing down a standalone component meant for animating the height. When, as a user, you look at the whole library then you will find that it is relatively small and can be applied in a very convenient manner.

1
2
3
4
5
6
7
<AnimateHeight
  duration={ 500 }
  height={ 'auto' }
>
  <h1>Your content goes here</h1>
  <p>Put as many React or HTML components here.</p>
</AnimateHeight>

React CSS Fade-in Transitions

Here, as an animation user, the foremost thing which is required to be done is to wrap down the whole component in the form of a TransitionGroup component. In this component, we place the prop to unmount or mount the dialog.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import React from "react";
import { TransitionGroup, CSSTransition } from "react-transition-group";
class Dialog extends React.Component {
  render() {
    const { isOpen, onClose, message } = this.props;
    return (
      <TransitionGroup component={null}>
        {isOpen && (
          <CSSTransition classNames="dialog" timeout={300}>
            <div className="dialog--overlay" onClick={onClose}>
              <div className="dialog">{message}</div>
            </div>
          </CSSTransition>
        )}
      </TransitionGroup>
    );
  }
}
javascript

Each of the times when isOpen is altered, there will be a change in the sequence of the class names that have taken place. This change will happen in the root element of the dialog.

When the user sets the classNames prop to fade, in this case, the fade-enter will be incorporated instantly prior to the mounting of the element and then via the command fade-enter-active the user can expect the transition to start. The user can observe the fade-enter-done command after the completion of the transition. The transition will basically function on the grounds of the timeout set. Precisely speaking, the same function will occur at the time when the element is unmounted through the exit class name group.

The application of this method simply leads to the CSS rules to generate our transitions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.dialog-enter {
  opacity: 0.01;
  transform: scale(1.1);
}

.dialog-enter-active {
  opacity: 1;
  transform: scale(1);
  transition: all 300ms;
}

.dialog-exit {
  opacity: 1;
  transform: scale(1);
}

.dialog-exit-active {
  opacity: 0.01;
  transform: scale(1.1);
  transition: all 300ms;
}
css

React CSS Transition Group: How It Interacts With Components

React CSS Transition Group basically interacts with the components in terms of customization. There are reusable components which can help in enable the component-specific themes, like default colors as well as its dimensions aligned to the component itself. Thereafter, each parent can handle styles and probably tweak their look.

While working CSS-in-JS, the styles could remain transient from parent to child in the matter of merging the existing style objects altogether.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* Button.jsx */
import styles from './Button.css.js';
static propTypes = {
  style: React.PropTypes.object  
};
render() {
  var style = Object.assign({},
    styles.button,
    this.props.style
  );
  return (<button style={style}/>);
}
/* ButtonVariant.css.js */
export default {
  button: {
    backgroundColor: 'red'
  }
}

/* ButtonVariant.jsx */
import Button from './Button.jsx';
import styles from './ButtonVariant.css.js';
render() { return (<Button style={styles.button}/>) }
javascript

In the CSS React Modules, the desired results can be acquired by concentrating their class names in a collective manner.

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
/* Button.jsx */
import styles from './Button.css';

static propTypes = {
  className: React.PropTypes.string  
};

render() {
  var className = [
    styles.button,
    this.props.className
  ].join(' ');

  return (<button className={className}/>);
}

/* ButtonVariant.css */
.button {
  background-color: red;
}

/* ButtonVariant.jsx */
import Button from './Button.jsx';
import styles from './ButtonVariant.css';
render() { return (<Button className={styles.button}/>) }
javascript

React CSS Animating a Page Switch

In order to accomplish the animation of the page switch, the user is going to be required to use a simple React CSS app wrapper that can enable routing. The user can apply BrowserRouter accessed from React Router in order to wrap the app. Here, it is critical to understand that BrowserRouter can only work if the web browser can render backing to the HTML5 history Application Programming Interface (API). We can verify it by seeing the page after fully refreshing it. The only setback with this application is that it will terminate the transitions existing in the older browsers, yet the website will function properly.

1
const supportsHistory = 'pushState' in window.history; 

React CSS Router is a little bit sloppy with the process of route matching. In order to neutralize this problem, the user is required to apply a switch component in order to ensure that each route is rendered one at a time. If there is any error in existence with pathless route then the user can identify them at the end of the switch.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const App = () => (
<BrowserRouter forceRefresh={!supportsHistory}>
  <div>
    <Nav />
    <main>
      <Switch>
        <Route
          exact
          path="/"
          component={Home}
        />
        <Route
          path="/about"
          component={About}
        />
        <Route
          component={Error404}
        />
      </Switch>
    </main>
  </div>
</BrowserRouter>
);

Once the application is set up, the user can make the navigation happening.

React CC Transition Group Working on Offset Animation Start Timing

There is a large amount of research and upgrading work is being done at the animation offset and it is expected that once attr and calc are completely supported, the user will be able to do it without JavaScript.

Presently, in the CSS transition it would be like:

1
2
3
4
.something > li
{
    animation: myAnimation 1s ease calc(0.5s * attr(data-animation-offset number 1));
}
css

The code will generate an effect in which every item animates what would seem to be a random order.

In order to fetch the desired results, in terms of effects, the user can work with the timings of the animations. To avail this effect, the user is required to apply data-wow-offset="50” or/and data-wow-delay="0.5s". In order to get different time effects, all the user is required is to play around with the numerical values.

One can do it as demonstrated below:

1
2
3
<div className="wow rubberBand" data-wow-offset="50” data-wow-delay="0.5s“>
 <h1>Stuff to move</h1>
</div>

The code provided here is merely the most basic, yet it can give the user fruitful results.

Conclusion

There is no limitation to the number of code and their scope of improvement if both novice and pro-coders apply them and explore the possibilities. As we have seen, the React CSS Transition Group can aid you with multiple components, themes, and functions. It is arguably the most conducive transition platform ever in existence.

References

The following resource has been referred to while writing this guide:

1