Stylized component response fades / fades

I am trying to create a React component to handle attenuation and attenuation. In the following code, if I pass out as a support for a component, it is disabled as hidden before the animation. I try to make it disappear by default and then fade when I went into out prop. Does anyone see a solution to this problem?

 import React from 'react'; import styled, { keyframes } from 'styled-components'; const fadeIn = keyframes` from { transform: scale(.25); opacity: 0; } to { transform: scale(1); opacity: 1; } `; const fadeOut = keyframes` from { transform: scale(1); opacity: 0; } to { transform: scale(.25); opacity: 1; } `; const Fade = styled.div` ${props => props.out ? `display: none;` : `display: inline-block;` } animation: ${props => props.out ? fadeOut : fadeIn} 1s linear infinite; `; function App() { return ( <div> <Fade>&lt;💅test&gt;</Fade> </div> ); } export default App; 

WebpackBin example

+7
reactjs styled-components
source share
1 answer

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}>&lt;💅test&gt;</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.

+9
source share

All Articles