Hello everyone, I am building a shop component that is several items that will later have their quantities changed in the cart section.
However the main problem behind this is the user can add several of these shops to the cart and it will overcharge them and confuse my client.
Is there a way I can make the ‘add to cart’ button only clickable once?
document.addEventListener('click', e => {
if (e.target.classList.contains('button')) {
this.props.addToCart(e)
}
});
}
Here is how the event listener works
addToCart (e) {
this.setState({
cartAmount: this.state.cartAmount + 1,
cart: [
...this.state.cart,
[e.target.value, e.target.name, e.target.id]
],
});console.log(this.state.cart)
}
And here is the function.
I am using an event listener because the buttons are being mapped from a JSON file. Using an onClick={} wouldn’t work.
Any help would be appreciated!
Are you setting event listeners in React with onClick
or are you using the DOM API directly?
I’ve never tried it before, but I assume you’d be able to set the onClick
callback dynamically.
<button onClick={hasAlreadyClicked ? null : addToCart} >
hasAlreadyClicked
being some boolean value that is initialized to false.
I can’t use any kind of onClick with these buttons, they’re being rendered after the component loads so if I use an onClick it will redscreen
I bet this is it.
Have you ever used these before?
document.addEventListener('click', e => {
if (e.target.classList.contains('button')) {
this.props.addToCart(e)
e.target.removeEventListener('click', e);
}
});
}
I am a little lost as to what I should put the second argument as
You should define the callback function for the click event.
function addToCart() {
// do stuff
document.removeEventListener('click', addToCart);
}
document.addEventListener('click', addToCart);
I doubt that you want to have the click event bound to the whole document though.
1 Like
I ultimately didn’t use your solution, however thanks for getting my noggin’ joggin’.
e.target.classList.remove('button')
That’s how i did it
1 Like
@Imstupidpleasehelp You can also pass options object to the event listener with a property “once” = true and the button will be clickable only once.
document.addEventListner(‘click’, clickHandler, { once: true })
Reference: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
1 Like