-1
I am creating a button in React that when clicking generates an effect ripple. I use the getBoundingClientRect
to pick up the position, but when I click a mouse very fast in the same place, the coordinates change and the effect appears randomly on the button.
How do I get the exact coordinates with clicks in the same place?
import React from 'react';
import { Button } from './styles'
const ReactButton = ({ children }) => {
const renderEffect = event =>{
const button = event.currentTarget;
const circleEffect = document.createElement('span');
const proportion = Math.max(button.clientWidth, button.clientHeight);
const radius = proportion / 2;
const rect = event.target.getBoundingClientRect();
circleEffect.style.width = `${proportion}px`;
circleEffect.style.height = `${proportion}px`;
circleEffect.style.left = `${Math.trunc(event.clientX - rect.left - radius) }px`;
circleEffect.style.top = `${Math.trunc(event.clientY - rect.top - radius) }px`;
circleEffect.classList.add('drop')
const drop = button.getElementsByClassName('drop')[0];
if(drop) {drop.remove()};
button.appendChild(circleEffect);
}
return (
<Button onClick={renderEffect}>
{children}
</Button>
)
}
export default ReactButton;
import styled, { keyframes } from 'styled-components'
const drop = keyframes`
to {
transform: scale(4);
opacity: 0;
}
`
export const Button = styled.button`
position: relative;
overflow: hidden;
background: #EA5E45;
transition: background 400ms;
color: #fff;
padding: 1rem 2rem;
font-size: 1rem;
outline: 0;
border: 0;
/* border-radius: 0.20rem; */
box-shadow: 0 0 0.5rem rgba(0,0,0,0.3);
cursor: pointer;
span.drop {
position: absolute;
border-radius: 50%;
transform: scale(0);
animation: ${drop} 600ms linear;
background: rgba(255, 255, 255, 0.7);
}
`;
Maybe
event.target
the second time is thecircleEffect
that you added the first time, try to make aconsole.log
to check whether theevent.target
is really what you expect it to be. Something likeconsole.log(event.target.tagName)
maybe already to check this.– Icaro Martins
Really @Icaromartins. I returned twice the same tag button causing this conflict. THANK YOU MY DEAR. I left it like this: Math.trunc(Event.clientX - button.getBoundingClientRect(). left - Radius)
– Luka Martins
Good that helped somehow =D, so now not to leave your question open you can: answer your question showing what was the problem and what was the solution, delete it or if there is still any problem update it by clicking on [Edit].
– Icaro Martins
is mixing different commands from those that the
React
uses ... will not be cool this and will bring you many problems– novic
I managed to solve with the tip of the friend. Thanks for the enormous strength
– Luka Martins