Published Jan 18 2019
When you work on a React functional component you might have the need to attach an event to onClick (or other events).
You usually do:
<button onClick={addBill}>Add</button>
But what if you have to pass a parameter? Say you have a list of bills, and you want to remove one by clicking the βXβ next to it.
You canβt do:
<button onClick={removeBill(index)}>π«</button>
because the expression inside onClick is going to be executed on mount. This is going to delete all the bills in the list, as soon as the app is started.
Instead, this is what you need to do, using arrow functions:
<button onClick={() => removeBill(index)}>π«</button>
I wrote an entire book on this topic π
© 2023 Flavio Copes
using
Notion to Site
Interested in solopreneurship?