Home > front end >  How to create temporary component React?
How to create temporary component React?

Time:01-17

I want to set an animation for each element created by clicking the background, of the website homepage (a ripple effect like raindrops falling on water), and disappear moments after. So far the solution I found was to unmount each component by setting a state to false, inside this child component. I have the feeling I'm using a really bad practice and I want to correct it.

Home ->

export interface Coordenates {
    x: number;
    y: number;
}
const Home: React.FC = () => {
    const [mousePositionArray, setMoussePositionArray] = useState<Coordenates[]>([])

    const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {

        setMoussePositionArray(
            mousePositionArray
                ? prev => [...prev, { x: e.pageX, y: e.pageY }]
                : [{ x: e.pageX, y: e.pageY }]
        )
    }

    return (
        <div onClick={handleClick} style={{ width: '100vw', height: '100vh', position: 'relative' }} >
            {mousePositionArray.map((position, i) => (
                <Ripple key={i} positionX={`${position.x}px`} positionY={`${position.y}px`} />
            ))}
        </div>
    )

};

Ripple component ->

interface Props {
    positionX: string;
    positionY: string;
}
const Ripple: React.FC<Props> = ({ positionX, positionY }) => {
    const [active, setActive] = useState(true);

    // Simulate callback on animation completion
    useEffect(() = {
        setTimeout(() => {
            setActive(false)
        }, 2000)
    }, []);

    if (!active) return null;

    return (
        <SVG positionX={positionX} positionY={positionY} >
            <g className="blob" >
                <path className="blob-path" d="M138.4, -233.9C176.8, -217.5, 203.6, -175.3, 225.7, -132C247.9, -88.7, 265.5, -44.3, 259.5, -3.3999999999999995C253.6, 37.5, 224.2, 75, 200.5, 115.6C176.7, 156.1, 158.6, 199.7, 126.1, 222.8C93.7, 245.9, 46.8, 248.5, 1.7999999999999998, 245.3C-43.2, 242.1, -86.3, 233.2, -127.3, 215C-168.3, 196.9, -207.1, 169.4, -227.1, 132.1C-247, 94.7, -248, 47.3, -249, -0.5999999999999996C-250, -48.5, -251, -97, -229.6, -131.8C-208.2, -166.6, -164.3, -187.6, -122.3, -201.9C-80.3, -216.1, -40.2, -223.6, 4.9, -232.1C50, -240.6, 100, -250.2, 138.4, -233.9 " fill="none" stroke="#F7770F" strokeWidth='6'>
                </path>
            </g>
        </SVG>
    )
};

Image: Rendered components stacking up

GIF: Rendered components stacking up

Intended result here

Appreciate all the suggestions.

CodePudding user response:

Put the Simulate callback on animation completion part in componentDidMount(). componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). That way count down will start only after component is ready.

CodePudding user response:

Use React.unmountComponentAtNode(document.querySelector(''));

  •  Tags:  
  • Related