ArticleZip > How To Add Ripple Effect When Clicking Card In Mui

How To Add Ripple Effect When Clicking Card In Mui

If you’re looking to add a little visual flair to your MUI app, incorporating a ripple effect when users click on cards can be a great way to enhance user experience. In this article, we'll walk you through the simple steps to achieve this effect in your React application using Material-UI.

Firstly, ensure you have Material-UI installed in your project. If not, you can easily add it by running the following command:

Bash

npm install @mui/material @emotion/react @emotion/styled

Once you have Material-UI set up, let's dive into adding the ripple effect to your cards. The ripple effect is a popular visual feedback technique where a wave-like animation emanates from the point of interaction when a user clicks on an element.

To begin, find the card component in your application where you want to implement the ripple effect. In the `Card` component, let's add the required event handler and styles to make the ripple effect work smoothly.

Jsx

import React from 'react';
import { Card } from '@mui/material';
import { RippleButton } from '@mui/core';

const MyCard = () => {
  const handleClick = (event) => {
    const ripple = document.createElement('span');
    const rect = event.currentTarget.getBoundingClientRect();
    const size = Math.max(rect.width, rect.height);
    const top = event.clientY - rect.top - size / 2;
    const left = event.clientX - rect.left - size / 2;

    ripple.style.width = ripple.style.height = `${size}px`;
    ripple.style.top = `${top}px`;
    ripple.style.left = `${left}px`;

    ripple.classList.add('ripple');

    event.currentTarget.appendChild(ripple);

    setTimeout(() => {
      ripple.remove();
    }, 600);
  };

  return (
    
      {/* Add your card content here */}
    
  );
};

export default MyCard;

In the above code snippet, we create a `handleClick` function that dynamically generates a `span` element to create the ripple effect at the location of the click inside the `Card` component. The ripple animation is then removed after 600 milliseconds to ensure a smooth user experience.

To enhance the visual aesthetics of the ripple effect, you can add the following CSS styles to your project:

Css

.ripple {
  position: absolute;
  background: rgba(0, 0, 0, 0.15);
  border-radius: 50%;
  transform: scale(0);
  animation: rippleEffect 0.6s linear;
}

@keyframes rippleEffect {
  to {
    transform: scale(5);
    opacity: 0;
  }
}

Used in conjunction with the JavaScript function, the CSS styles define the appearance and behavior of the ripple effect, creating a visually appealing interaction for users.

By following these steps, you can easily implement a ripple effect when clicking on cards in your Material-UI app, elevating the overall user experience and adding a touch of interactivity to your application. Give it a try and see the difference it makes!

×