Fade out on delete
To implement fade out on delete, you need 2 steps:
- Slowly hide the HTML element by reducing its opacity from 1 to 0.
- Then, remove the HTML element when it is completely hidden. i.e. Re-render UI without it.
Implementation: Fade out and delete single element
Live Demo
Code: fade-out-on-delete-demo.jsx
import React, { useState } from 'react';export default function FadeOutOnDelete() {const [isFadingOut, setIsFadingOut] = useState(false);const [showButton, setShowButton] = useState(true);const handleDeleteClick = () => {setIsFadingOut(true);// Delay the actual deletion to allow fade-out animationconst timerId = setTimeout(() => {setShowButton(false);}, 1000+3); // Match this duration to your CSS transition};const fadeOutCss = { opacity: 0, transition: "opacity 1s ease-out" }return (<div style={(isFadingOut)? fadeOutCss: {}}>{showButton &&<button className='btn btn-primary m-1'onClick={handleDeleteClick}>Click me to Delete</button>}</div>);}
Implementation: Fade out and delete multiple elements
Same principle as the preceding example. I just create 2 lists to keep track of the buttons states and the fading states.
Don't try to directly manipulate the DOM to change the styling. For my first try, I use
event.target.style.cssText = "opacity: 0; transition: opacity 1s ease-out";
to trigger a change
but the timing for the fading and deletion is off. I recommend to stick to the React state.
Live Demo
Code: fade-out-on-delete-from-list-demo.jsx
import { CodeSquare } from 'lucide-react';import React, { useState } from 'react';export default function FadeOutOnDeleteFromList() {// Create fadingOutObject by using button names as key.const buttonNames = [1,2,3];const fadingOutObjectInit = buttonNames.reduce((acc, currValue)=>{acc[currValue] = false;return acc;}, {});const [buttonsList, setButtonsList] = useState([1, 2, 3]);const [fadingOutObject, setFadingOutObject] = useState(fadingOutObjectInit);const fadeOutCss = { opacity: 0, transition: "opacity 1s ease-out" }; // transition for 1 sec.const handleDeleteClick = (nameToDel) => {// Trigger state change to fade out.const newfadingOutObject = structuredClone(fadingOutObject);newfadingOutObject[nameToDel] = true;setFadingOutObject(newfadingOutObject);// Delay deletion action.const timerId = setTimeout(() => {const newButtonsList = buttonsList.filter((name) => name !== nameToDel);setButtonsList(newButtonsList);}, 1000 + 3); // Match this duration to your CSS transition};return (<div>{buttonsList &&buttonsList.map((name, idx) => (<button className='btn btn-primary m-1'key={idx}onClick={() => { handleDeleteClick(name) }}style={(fadingOutObject[name]) ? fadeOutCss : {}}>Click me to Delete {name}</button>))}</div>);}