I’ve started to get the hang of React and ES6, but it’s only been three weeks and there are of course tons and tons of things I haven’t learned yet. I’ll go over a couple of things that I think anyone starting to learn React could benefit from. In this blog post I’ll go over Button Clicks.
You might be encountering a couple errors:
- onClick function triggering when button loads
- The onClick function doesn't recognize the function its supposed to trigger
- The function refreshes the page
- You can't pass parameters into the function
See the corresponding number below for potential solutions and explanations.
1. Prevent onClick from automatically running
The reason it automatically runs is because you are triggering the function when referencing it. Your code may look like this:
The parentheses indicate that the function should be executed. When the page loads, it sees the parenthesis and runs the corresponding function. To fix the issue, simply remove the parenthesis. To pass parameters in, see the section below.
2. Force onClick to recognize function
at the end of
See example below.
3. Prevent Auto-Refresh
Simply use the: preventDefault() function
4. Passing Parameters
Add the parameters in the .bind(this) as seen below