React: How to animate the change of the component rendered?
11,853
You can do with ReactCSSTransitionGroup like provided in this section
Your css:
.example-enter {
opacity: 0.01;
}
.example-enter.example-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.example-leave {
opacity: 1;
}
.example-leave.example-leave-active {
opacity: 0.01;
transition: opacity 300ms ease-in;
}
Will look like this:
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
class MyComponent extends Component {
constructor (props) {
super(props)
this.state = { currentComponent: 1,
numberOfComponents: 2}
}
componentWillMount() {
setInterval(() => {
if(this.state.currentComponent === 2) {
this.setState({currentComponent: 1})
} else {
this.setState({currentComponent: this.state.currentComponent + 1})
}
}, 5000)
}
render(){
let currentComponent = null;
if(this.state.currentComponent === 1) {
currentComponent = <ComponentOne/>;
} else {
currentComponent = <ComponentTwo/>;
}
return(
<ReactCSSTransitionGroup
transitionName="example"
transitionEnterTimeout={500}
transitionLeaveTimeout={300}>
{currentComponent}
</ReactCSSTransitionGroup>
)
}
}
Author by
criver.to
Updated on June 26, 2022Comments
-
criver.to almost 2 years
I change the component that is rendered through a time interval.
I would like to be able to add an animation every time that change happens. What is the best way to go about it?
constructor (props) { super(props) this.state = { currentComponent: 1, numberOfComponents: 2} } componentWillMount() { setInterval(() => { if(this.state.currentComponent === 2) { this.setState({currentComponent: 1}) } else { this.setState({currentComponent: this.state.currentComponent + 1}) } }, 5000) } render(){ let currentComponent = null; if(this.state.currentComponent === 1) { currentComponent = <ComponentOne/>; } else { currentComponent = <ComponentTwo/>; } return( currentComponent ) }
EDIT:
Also when trying to use 'react-addons-css-transition-group' I get the following error:
-
criver.to over 7 yearsThanks. Thats what I attempted but every time I import that library. I keep getting the following error: Uncaught TypeError: React.PropTypes.shape is not a function
-
Lucas Katayama over 7 yearsThis error is probably somewhere else... Where do you have Protypes definitions in you app?
-
criver.to over 7 yearsI actually get it from the library. I added the error screenshot on my post.
-
Lucas Katayama over 7 yearsWhich versions of react and react-transitions are you using?
-
criver.to over 7 years
-
Lucas Katayama over 7 yearsI don't know... could you send me a repo so I run it here?