Making a button clickable only once

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 ('button')) {

Here is how the event listener works

addToCart (e) {
        cartAmount: this.state.cartAmount + 1,
        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

There’s this:

1 Like

I bet this is it.
Have you ever used these before?

document.addEventListener('click', e => {
      if ('button')) {
        this.props.addToCart(e)'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’.'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 })


1 Like