How to add ripple effect in react js?
August 23, 2024Hi Friends π,
Welcome To aHoisting!
To add ripple effect in react js, you can use animation: ripple-animation 0.6s linear;
. It will add ripple effect in react js.
Today, I am going to show you, how to add ripple effect in react js.
Table of contents
- Install and create a new React app.
- Import react component.
- Create a Component.
Letβs start with the first step.
Step 1: Install and create a new React app.
First you have to install the React project. You should use create-react-app
command to create a new React project.
npx create-react-app my-app
cd my-app
npm start
Step 2: Import react component.
After installing, you have to import your React component.
import React from 'react';
import RippleButton from './RippleButton';
import React, { useState, useRef } from 'react';
import './App.css';
Step 3: Create a Component.
You can use className="App"
to add ripple effect in react js.
<div className="App">
<RippleButton>Click Me</RippleButton>
</div>
Add ripple effect example.
The below code is an example of a React. You have to import ./RippleButton'
and set animation: ripple-animation 0.6s linear;
to add ripple effect in react js.
App.js
import React from 'react';
import RippleButton from './RippleButton';
function App() {
return (
<div className="App">
<RippleButton>Click Me</RippleButton>
</div>
);
}
export default App;
RippleButton.js
import React, { useState, useRef } from 'react';
import './App.css';
function RippleButton({ children }) {
const [ripples, setRipples] = useState([]);
const buttonRef = useRef(null);
const createRipple = (event) => {
const button = buttonRef.current;
const rect = button.getBoundingClientRect();
const size = Math.max(button.clientWidth, button.clientHeight);
const x = event.clientX - rect.left - size / 2;
const y = event.clientY - rect.top - size / 2;
const newRipple = {
x,
y,
size,
};
setRipples((prevRipples) => [...prevRipples, newRipple]);
setTimeout(() => {
setRipples((prevRipples) => prevRipples.slice(1));
}, 600); // Remove the ripple after the animation
};
return (
<button className="ripple-button" onClick={createRipple} ref={buttonRef}>
{children}
{ripples.map((ripple, index) => (
<span
key={index}
className="ripple"
style={{
left: ripple.x,
top: ripple.y,
width: ripple.size,
height: ripple.size,
}}
/>
))}
</button>
);
}
export default RippleButton;
App.css
.ripple-button {
position: relative;
overflow: hidden;
padding: 10px 20px;
border: none;
background-color: #6200ea;
color: white;
font-size: 16px;
cursor: pointer;
outline: none;
}
.ripple {
position: absolute;
border-radius: 50%;
background-color: rgba(255, 255, 255, 0.7);
transform: scale(0);
animation: ripple-animation 0.6s linear;
}
@keyframes ripple-animation {
to {
transform: scale(4);
opacity: 0;
}
}
In the above code example, I have used the animation: ripple-animation 0.6s linear;
to add ripple effect in react js.
Check the output of the above code.
All the best π