Is there a method of disabling a button in ReactJS after a certain number of clicks?

Viewed 49

I'm relatively new to React and I was working on a button that duplicates a component I created when clicked, but I want to limit the user to only be allowed to click on said button a set number of times (say 4 times) before the button is non-functional/removed. Here's a code snippet if it helps; is this possible? I thought about having a counter, but how would I implement that alongside the button?

Many thanks!

function App() {
  const [inputList, setInputList] = useState([]);

  const onAddBtnClick = event => {
    setInputList(inputList.concat(<Autocomplete items={foods} />));
  };

  return (
    <Fragment>
      <div className="foodcompleter">
        <Button onClick={onAddBtnClick} variant="primary" size="lg" block>Add Food</Button> 
        {inputList}
      </div>
    </Fragment>
  );
}
3 Answers

You can basically check if inputList.length === 4, then you disable the button

You can create your component CustomButton with a state that saves the number of clicks and after each state change just validate if the number of clicks is equal to your desired value.

You could remove the event listener after the click

const onKeyDown = (event) => { console.log(event) }

useEffect(() => {
window.addEventListener('keydown', onKeyDown)

return () => { window.removeEventListener('keydown', onKeyDown) }
}, [])
Related