The React-Transition-group provides a simple component for defining animations. The library does not define styles per se, but instead manipulates the DOM in useful ways to make transitions and animations more comfortable. In other words, react-transition-groups provide a simpler way to animate and transition.
The installation
// npm
npm install react-transition-group --save
// yarn
yarn add react-transition-group
Copy the code
Official offer four components, the Transition, respectively, CSSTransition, SwitchTransition, TransitonGroup.
Transition
The Transition component allows you to describe transitions from one component state to another over time using a simple declarative API. Most commonly, it is used for mounting and unmounting animation components, but can also be used to describe in-place transition state.
Note :Transition is a platform-independent base component. If you use transitions in CSS, you may want to use TRANSITIONS in CSS. It inherits all the features of Transition, but includes other features necessary to better handle CSS transitions (hence the name of the component).
By default, the Transition component does not change the behavior of the components it presents; it only tracks the “in” and “out” states of components. It’s up to you to give those states meaning and effect. For example, we can add styles to a component as it enters or exits.
There are four main states in a transition:
- entering
- entered
- exiting
- exited
The transition state is switched through the IN attribute. When true, the component begins the “Enter” phase. In this phase, components move from the current transition state to the “in” state during the transition, and then to the “in” state again after the transition is complete.
import { Transition } from 'react-transition-group';
const duration = 300;
const defaultStyle = {
transition: `opacity ${duration}ms ease-in-out`.opacity: 0,}const transitionStyles = {
entering: { opacity: 1 },
entered: { opacity: 1 },
exiting: { opacity: 0 },
exited: { opacity: 0}};const Fade = ({ in: inProp }) = > (
<Transition in={inProp} timeout={duration}>
{state => (
<div style={{
. defaultStyle.. transitionStyles[state]
}}>
I'm a fade Transition!
</div>
)}
</Transition>
);
Copy the code
parameter | instructions | type | The default value |
---|---|---|---|
children | Instead of the React element, you can use a function that can be used to apply code-specific props to components by calling the function with the current transition state (‘ Enter ‘, ‘Enter’, ‘exit’, ‘exited’, ‘unmount’). | Function | element |
in | For display components; Triggers the enter or exit state. | boolean | false |
mountOnEnter | By default, the child component is mounted immediately along with the parent transformation component. If you want to “delay mount” the first component on in={true}, you can set mountOnEnter. After entering the transformation for the first time, the component will remain mounted, even in the exit state, unless you also specify unmountOnExit. | boolean | false |
unmountOnExit | By default, child components remain mounted after reaching the exit state. If you want to uninstall the component after it exits, set unmountOnExit. | boolean | false |
appear | Normally, if a component is displayed when it is mounted, the component is not transformed. True if you want to convert on the first mount set, and the component will be converted immediately after the < Transition > mount.Note: There is no specific “show” state. Appear just adds an additional Enter transform. | boolean | false |
enter | Enable or disable the Enter conversion. | boolean | true |
exit | Enable or disable the Exit transformation. | boolean | true |
timeout | The duration of the conversion in milliseconds. | number | { enter? : number, exit? : number, appear? : number } |
addEndListener | Add a custom conversion end trigger. Call using the DOM node being converted and the done callback. Allows more fine-grained transition termination logic. Note: If a timeout is provided, it is still used as a fallback. | Function | |
onEnter | The callback that is triggered before the Input state is applied. An additional parameter isAppearing is provided to indicate whether the Enter stage occurred on the initial mount. | Function(node: HtmlElement, isAppearing: bool) | function noop() {} |
onEntering | The callback that is triggered in the application input state. An additional parameter isAppearing is provided to indicate whether a entering phase has occurred on the initial mount. | Function(node: HtmlElement, isAppearing: bool) | function noop() {} |
onEntered | The callback that is triggered after applying the Input state. An additional parameter isChatting is provided to indicate whether an Entered phase has occurred on the initial mount. | Function(node: HtmlElement, isAppearing: bool) | function noop() {} |
onExit | The callback that is triggered before the Exit status is applied. | Function(node: HtmlElement) -> void | function noop() {} |
onExiting | The callback that is triggered in the application Exit state. | Function(node: HtmlElement) -> void | function noop() {} |
onExited | The callback that is triggered after the Exit status is applied. | Function(node: HtmlElement) -> void | function noop() {} |
CSSTransition
This Transition component is used for CSS animation transitions, inspired by the NG-Animate library.
CSSTransition: The CSSTransition component applies a series of classnames to describe the actions when it fades into appear, enters enter, and exits. First appear is applied to the component className, then the “active” className is added to activate the CSS animation. After the animation completes, the original class changes to done to indicate that the component animation has been applied and loaded.
When the component’s in property changes to true, the component’s className is assigned to example-Enter, and the CSS class name of example-Enter-active is added at the next moment. These are conventions based on the className attribute. If the original component has className=” rotate-rotate “, it changes to “rotate-enter” in the enter state.
//index.js
import React,{ Component } from 'react'
import CSSTransition from 'react-transition-group/CSSTransition'
import './css/index.css'
export default class App extends Component {
state = {
show: true
}
render () {
return (
<CSSTransition
in={this.state.show}
classNames='show'
timeout={300}
unmountOnExit>
{state => {
// console.log(state)
return (
<div className='circle' onClick={()= >this.setState(state=>({show: ! state.show}))}> show</div>)}}</CSSTransition>)}}//index.css
.circle {
margin: 2px;
width: 50px;
height: 50px;
position: absolute;
display: inline-block;
left: 100px;
box-shadow: 0px 1px 2px #999;
text-shadow: 0px 1px 2px #999;
line-height: 80px;
text-align: center;
color: white;
font-size: 10px;
}
.show-enter {
opacity: 0.01;
transform: scale(0.9) translateY(50%);
}
.show-enter-active {
opacity: 1;
transform: scale(1) translateY(0%);
transition: all 300ms ease-out;
}
.show-exit {
opacity: 1;
transform: scale(1) translateY(0%);
}
.show-exit-active {
opacity: 0.01;
transform: scale(0.9) translateY(50%);
transition: all 300ms ease-out;
}
Copy the code
parameter | instructions | type | The default value |
---|---|---|---|
in | The react component is assigned a value for the properties of the animation. The react component state is changed to turn the animation on and off. | boolean | false |
classNames | The classNames attribute is used when a component is animated. The different animation states (Enter,exits,done) are suffixed to form a new className. Such as: ClassName =”fade” will be applied to fade-enter,fade-enter-active,fade-enter-done,fade-exit,fade-exite-active,fade-exit-done, Fade – appear and fade – appear – active. Each independent className corresponds to a separate state. | string | { appear? : string, appearActive? : string, enter? : string, enterActive? : string, enterDone? : string, exit? : string, exitActive? : string, exitDone? : string, } |
onEnter | The component’s callback function, called immediately when the component enters or Appears. | Function(node: HtmlElement, isAppearing: bool) | |
onEntering | The component’s callback function, called immediately when enter-active or appearance-active. | Function(node: HtmlElement, isAppearing: bool) | |
onEntered | Component callback functions, which are called immediately when component Enter,appearclassName are removed. | Function(node: HtmlElement, isAppearing: bool) | |
onExit | This function is called when the component applies the exit class name. | Function(node: HtmlElement) | |
onExiting | This function is called when the component applies the exit-Active class name. | Function(node: HtmlElement) | |
onExited | This function is called when the component exit class name is removed and an exit-done class name is added. | Function(node: HtmlElement) | |
mountOnEnter | By default, the child component is mounted immediately along with the parent transformation component. If you want to “delay mount” the first component on in={true}, you can set mountOnEnter. After entering the transformation for the first time, the component will remain mounted, even in the exit state, unless you also specify unmountOnExit. | ||
unmountOnExit | By default, child components remain mounted after reaching the exit state. If you want to uninstall the component after it exits, set unmountOnExit. | ||
appear | If a component is displayed when it is mounted, the component is not transformed. If you want to convert on the first mount set, it will be true, and the component will be converted immediately after the < transition > mount. Note: there is no specific “display” state. Appear just adds an additional Enter transform. | boolean | false |
The animation properties | instructions |
---|---|
.xxx-enter | Loading animation before entry |
.xxx-enter-active | The process from the entrance to the end of the entrance |
.xxx-enter-done | After the completion of the entry animation |
.xxx-exit | Load the animation before appearing |
.xxx-exit-active | The process from the entrance to the end of the entrance |
.xxx-exit-done | After the animation is executed |
SwitchTransition
Transformation components inspired by the VUE transformation pattern. You can use it when you want to control rendering between state transitions. SwitchTransition converts consistently between the selected mode and the key of the child node (Transition or cstransition component).
If out-of-in mode is selected, SwitchTransition waits for the old child node to leave, and then inserts the new child node. If in-out mode is selected, SwitchTransition first inserts a new child node, waits for the new child node to enter, and then deletes the old child node.
Note: If you want the animation to happen at the same time (that is, remove the old child element and insert the new child element at the same time), you should use TransitionGroup.
function App() {
const [state, setState] = useState(false);
return (
<SwitchTransition>
<CSSTransition
key={state ? "Goodbye.world!" : "Hello.world!" }addEndListener={(node, done) = > node.addEventListener("transitionend", done, false)}
classNames='fade'
>
<button onClick={()= >setState(state => ! state)}> {state ? "Goodbye, world!" : "Hello, world!" }</button>
</CSSTransition>
</SwitchTransition>
);
}
.fade-enter{
opacity: 0;
}
.fade-exit{
opacity: 1;
}
.fade-enter-active{
opacity: 1;
}
.fade-exit-active{
opacity: 0;
}
.fade-enter-active,
.fade-exit-active{
transition: opacity 500ms;
}
Copy the code
parameter | instructions | type | The default value |
---|---|---|---|
mode | Transition mode. Out-in: The current element is first moved out, and then the new element is moved in when finished. In-out: The new element is converted in first, and the current element is converted out when finished. | out-in | in-out |
children | Any Transition or CSSTransition component. | element |
TransitionGroup
Components manage a set of transformation components (< transition > and < cstransition >) in a list. Like a transformation component, is a state machine that manages the mounting and unmounting of components over time.
In the following example, internal prop will be switched automatically when an item is deleted or added to TodoList.
Notice that no animation behavior is defined! How a list item is animated depends on the individual transformation component. This means you can mix and match animations for different list items.
//index.js
import React,{ Component } from 'react'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import './css/index.css'
export default class App extends Component {
state = {
items: [{id: 1.text: 'Buy eggs' },
{ id: 2.text: 'Pay bills' },
{ id: 3.text: 'Invite friends over' },
{ id: 4.text: 'Fix the TV' },
]
}
render () {
const { items } = this.state
return (
<div className='container'>
<TransitionGroup className="todo-list">
{items.map(({ id, text }) => (
<CSSTransition
key={id}
timeout={500}
classNames="show"
unmountOnExit>
<div className="todo-list-item">
<button
className='cancle'
onClick={()= >{ this.setState(state => ({ items: state.items.filter( item => item.id ! == id ), })); }} >×
</button>
<span className='item-text'>{text}</span>
</div>
</CSSTransition>
))}
</TransitionGroup>
<button
className='add'
onClick={()= > {
const text = prompt('Enter some text');
if (text) {
this.setState(state => ({
items: [
...state.items,
{ id: 1123, text },
],
}));
}
}}>
Add Item
</button>
</div>)}}//index.css
.show-enter {
opacity: 0.01;
}
.show-enter-active {
opacity: 1;
transition: all 300ms ease-out;
}
.show-exit {
opacity: 1;
}
.show-exit-active {
opacity: 0.01;
transition: all 300ms ease-out;
}
.container {
position: absolute;
top: 20px;
left: 100px;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px 1px rgb(202.202.202);
}
.todo-list {
border-radius: 5px;
box-shadow: 0 0 5px 1px rgb(202.202.202);
}
.todo-list-item {
height: 35px;
line-height: 35px;
padding: 0 10px;
border-bottom: 1px solid rgb(202.202.202);
}
.todo-list-item:last-of-type {
border-bottom: 0;
}
.item-text {
margin-left: 10px;
}
.cancle {
border: 0;
color: #fff;
background-color: #F04134;
border-radius: 3px;
box-shadow: 0 0 5px 1px rgb(202.202.202);
}
.add {
border: 0;
height: 30px;
line-height: 30x;
width: 120px;
margin-top: 15px;
font-size: 14px;
border-radius: 3px;
box-shadow: 0 0 5px 1px rgb(202.202.202);
}
Copy the code
parameter | instructions | type | The default value |
---|---|---|---|
component | Default ‘div’ (i.e. TransitionGroup) renders the div tag, which can also be changed, e.g. Component =”span” renders the SPAN tag. If you use React v16+ and want to avoid div element newlines, you can pass in Component ={null}. | any | div |
children | The component given can be a string or a custom component. | any | |
appear | Enable or disable the Show/Appear animation for all children. Note that specifying this parameter overrides any default Settings on the individual child transformations. | boolean | |
enter | Enable or disable enter/Enter animation for all children. Note that specifying this parameter overrides any default Settings on the individual child transformations. | boolean | |
exit | Enable or disable exit /exit animation for all children. Note that specifying this parameter overrides any default Settings on the individual child transformations. | boolean | |
childFactory | If you need to update a child when it leaves, it can provide a childFactory to wrap each child, even those that are about to leave. | Function(child: ReactElement) -> ReactElement | child => child |