Use React Transition Group alongside the Styled Components library

Rory Smith
InstructorRory Smith
Share this video with your friends

Social Share Links

Send Tweet

It’s possible to use React Transition Group alongside Styled Components. This can be useful should you want to use <CSSTransition> but are also taking advantage of the Styled Components library. In this lesson, we are going to take a look at the styled-transition-group library in order to achieve this.

Instructor: [00:00] In this example, we have a menu button which, when clicked, toggles the appearance of a menu using a transition with CSSTransition from react-transition-group. This example uses vanilla CSS to achieve the transition.

[00:18] Let's say instead we want to use styled-components to achieve the same thing. We will refactor our index.js and our index.css to use styled-components.

[00:30] First, we'll create a new file called "components.js." We'll grab all our CSS. We'll place it inside components.js. Now let's import styled from styled-components. What we need to do is turn these CSS blocks into styled-components.

[00:52] Here's an example with the toggler, which is a button. It becomes a Toggler component, which is a styled button. We pass it a template string. Let's apply the same principle to the rest of the CSS in this file.

[01:10] Now we have a Container component that contains our variables, the Toggler component, which accounts for the active state using props instead of a modifier class name, which is what we had before, and the List and ListItem components.

[01:28] In order to refactor our transition CSS, i.e., these four blocks, we need to make use of a separate package, styled-transition-group. Let's import that now.

[01:42] We'll import transition from styled-transition-group. This is going to allow us to use styled-components alongside react-transition-group.

[01:51] Now we can refactor our transition CSS. Now we have a Menu component with the styles as before. We're using a transition.div. The selectors here are slightly different to account for the library.

[02:09] Our styled-components are set up now. Let's head over back to our index.js, where we'll need to do some refactoring to account for styled-components. We're no longer going to need the imports to CSSTransition, class names, or index.css.

[02:28] Instead, we're going to import the styled-components that we just wrote. Down in our render, we're going to replace class names and elements with their corresponding styled-components names.

<[02:46] div className="container"> becomes Container. Let's apply that to the rest of the render method now. Now let's save and refresh. Now our example is working with styled-components.