Using ReactCSSTransitionGroup with a styled component

I use styled-components instead of the traditional css way. But I do not know how it can work together with the ReactCSSTransitionGroup .

Basically, it ReactCSSTransitionGroupsearches for specific class names in the css resource, and then applies to the component throughout the life cycle. However, since styled-componentsthere are no class names, styles are applied to components directly.

I know that I can choose not to use ReactCSSTransitionGroupit because this method does not look compatible. But when I use only styled-components, it seems that I can not display the animation when the component is unmounted - it is pure css, cannot access the component life cycle.

Any help or recommendation appreciated.

+4
source share
3 answers

Use a injectGlobal()helper style method where your React app loads. Using this method, you can create any CSS selector as if you were using regular CSS.

First create a JS file exporting a template literal with your CSS for react-transition-group(please don't use v2.1 new class name syntax):

globalCss.js

const globalCss = `
    .transition-classes {
        /* The double class name is to add more specifity */
        /* so that this CSS has preference over the component one. */
        /* Try removing it, you may not need it if properties don't collide */
        /* https://www.styled-components.com/docs/advanced#issues-with-specificity */

        &-enter&-enter {
        }

        &-enter&-enter-active {
        }

        &-exit&-exit {
        }

        &-exit&-exit-active {
        }
    }
`;

export default globalCss;

Then in your entry point file:

index.jsx

import { injectGlobal } from "styled-components";
import globalCss from "./globalCss.js";

injectGlobal`${ globalCss }`; // <-- This will do the trick

ReactDOM.render(
    <Provider store={ Store } >
        <HashRouter >
            <Route path="/" component={ Component1 } />
            <Route path="/" component={ Component2 } />
        </HashRouter>
    </Provider>,
    document.getElementsByClassName("react-app")[0]
);

However, if you just use CSS / SASS / Less to write classes for react-trasition-groupeven when using stylized components, it also works well.

+2
source

css . :

const Animation = styled(ReactCSSTransitionGroup)`
  ${({ transitionName }) => `.${transitionName}-enter`} {
    opacity: 0;
  }

  ${({transitionName}) => `.${transitionName}-leave`} {
    opacity: 1;
  }
`

const animationID = 'some-hashed-text'

const AnimationComponent = props => (
  <Animation
    transitionName={animationID}
    transitionEnterTimeout={0.1}
    transitionLeaveTimeout={2000}
  >
    <div>some content</div>
  </Animation>
)
Hide result
0

Try using camelCase in CSS as shown below.

.enter {

}
.enterActive { }
-1
source

Source: https://habr.com/ru/post/1671758/


All Articles