A few months ago I was watching a video on FrontendMasters about Qwik by Miško Hevery, and it caught my attention that, even though it’s a library similar to React, they used the “good” (😄) event to update the state of an input.
onChange
is one of the most commonly used events in React, and it’s very common to see it in combination with the state of an input.
So, what’s the difference between using input
vs change
?
Both events are very similar, as both are triggered when the value of an HTML element changes. The differences are:
oninput
is triggered when the value of an HTML element changes immediately.onchange
is triggered when the value of an HTML element changes and the element loses focus.
We can see it in a very simple example:
<!DOCTYPE html>
<html>
<body>
<input type="text" oninput="handleOnInput()" onchange="handleOnChange()" />
</body>
<script>
const input = document.querySelector("input");
function handleOnInput() {
input.style.color = "red";
}
function handleOnChange() {
input.style.color = "blue";
}
</script>
</html>
Start writing inside the input.
Text will change to red when you use oninput
and to blue when you use onchange
.
But wait a second you say. I have developed a React application and onChange updates the state of the input immediately. Why is that?
Well… That’s a design decision by React team.
onChange
is used to update the state not only of <input>
, <textarea>
, or <select>
, but also of any kind of component that uses state.
From their official documentation:
The onChange event behaves as you would expect it to: whenever a form field is changed, this event is fired. We intentionally do not use the existing browser behavior because onChange is a misnomer for its behavior and React relies on this event to handle user input in real time.
Like all DOM events, the
onChange
prop is supported on all native components and can be used to listen to bubbled change events.Note:
For
<input>
and<textarea>
,onChange
supersedes — and should generally be used instead of — the DOM’s built-inoninput
event handler.
You can read more about this in this discussion on the React GitHub.
If at any time you need to use something like the vanilla JavaScript onchange
event in React instead of triggering a event on every keystroke, you can use the onBlur
method that executes when the element loses focus on it.
It’s always a good idea to review the fundamentals of JavaScript from time to time.