DEV Community

Cover image for One major key that will amplify your coding prowess.
Jimster397
Jimster397

Posted on

One major key that will amplify your coding prowess.

OnChange vs OnClick within React:

When traversing through one of the advanced deliverables in my 2nd coding challenge at Flatiron school I realized there is a big difference between OnChange and OnClick. The deliverable asks you to create a sorting feature with a checkbox that changes the orientation of how certain cards are organized. This seemed simple at first to be an OnChange event since the page was changing its state however, the onChange event did not work.

Why did this happen?

The state of the page changes yet on onChange did not work. This is due to the special events that happen under the hood of react. The method that was called was .sort() and onChange causes the page to lose focus of the event that you are calling. When an onClick event occurs it allows for the .sort() to happen on the event that you are calling.

This ties into the difference between setting state and calling that state.

When setting the state we use a const variable and set it to this. const [variable, setVariable]= useState(true). This setVariable is what we use when we want to call the state of the page and in this situation we set it to true. This page will automatically have everything rendered until we set a onClick or onChange to our components.

Once we call that OnChange event to our page it attempts to find the state of the page and change it order for the change to occur. However, the detriment to this is that the when it changes and attempts to find the state of the page again it fails. Again as previously said it is because onChange loses the focus of what it is changing. The onChange event fires with the old value still attached to the checkbox where onClick triggers setting the new value and changing it and setting the focus back to the checkbox.

In conclusion, whenever you need to sort a page through a checkbox it is critical to use onClick however, some other programmers have gotten onChange to work, but it requires more effort and more coding. Knowing the differnce between these two OnChange and OnClick gives insight into how both work and how they interact with useState.

Here is the link to a Stack Overflow when encountering this issue.

Top comments (0)