Cross Fading conditionally rendered react components.
Here’s how you can smoothly transition react component during mounting and un-mounting. All this, without any third party library.
In most of the cases we tend to render a react component based on some condition. Some examples:
{showProduct && <Product />}{data.length && <List />
Code wise everything is right. But in UX point of view it’s not as good as we want.
Let me show this by an example. I’ve a Product
component, and I am rendering it based on state
showProduct
.
Now, lets see the behaviour in browser:
As you can see, Product
component is toggling with every click. But it is not good to our eye. The component is vanishing immeditaley, giving a feeling of flickering.
We can easily avoid such situations with cross fade animation by modifying our code little bit.
Cross fading animation for conditionally rendered react Component
Let us see the end result first, so that you can decide to further read the article or you can save your time:
In order to acheive cross fade animation, we have to do few changes in both of our component. (Parent component and the component which we want to render conditionally.
Key Points:
1. We have to add some simple fade in/out animation
2. Change the implementation of handleClose
in parent component.
3. First hide
the component, and once it is hidden only then change the state showProduct.
Change 1: Add these style in your css/scss
file.
Change 2: Introduce a new variable to hold the className . which will be responsible for showing and hiding the conditionally rendered component.
Change 3: Change the implementation of handleClose
.
Change 4: Pass onClose
and className
props to Product
Component.
Change 6: Create ref
for conditionally rendered component. This will be used to add listener to check if animation has been ended or not.
Change 7. In Conditionally Rendered component. In our case it is Product
. Under the componentDidMount ( useEffect) add event listener for animationEnd.
Change 8: Pay attention to {once:true}
, this will make sure my listener runs only once, due to this we don’t have to remove it.
Change 9: On animationEnd
if it is closing animation, then simple call the onClose
animaton.
Here is the final code: