The problem with your code is that you set the display property to none when props.out is true. That’s why you don’t see the animation, because before that even you can already hide the component!
The way to create fade-in animations is to use the visibility property instead and switch to the same amount of time as the animation. (see this old SO answer )
Something like this should solve your problems:
const Fade = styled.default.div` display: inline-block; visibility: ${props => props.out ? 'hidden' : 'visible'}; animation: ${props => props.out ? fadeOut : fadeIn} 1s linear; transition: visibility 1s linear; `;
const fadeIn = styled.keyframes` from { transform: scale(.25); opacity: 0; } to { transform: scale(1); opacity: 1; } `; const fadeOut = styled.keyframes` from { transform: scale(1); opacity: 1; } to { transform: scale(.25); opacity: 0; } `; const Fade = styled.default.div` display: inline-block; visibility: ${props => props.out ? 'hidden' : 'visible'}; animation: ${props => props.out ? fadeOut : fadeIn} 1s linear; transition: visibility 1s linear; `; class App extends React.Component { constructor() { super() this.state = { visible: true, } } componentDidMount() { setTimeout(() => { this.setState({ visible: false, }) }, 1000) } render() { return ( <div> <Fade out={!this.state.visible}><💅test></Fade> </div> ); } } ReactDOM.render( <App />, document.getElementById('root') )
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script> <div id="root" />
Note. Your fadeOut animation has also changed from 0 to 1 opacity, and not vice versa. I also fixed this in the snippet.
mxstbr
source share