How React onchange events work

Posted on October 14, 2020


The onChange event handler is a prop that you can pass into JSX’s input elements. In React, onChange is used to handle user input in real-time.

If you want to build a form in React, you need to use this event to track the value of input elements.

Here’s how you add the onChange handler to an input:

import React from "react"

function App(props) {
  return (
    <input 
      type="text" 
      name="firstName" 
      onChange={ (event) => console.log("onchange is triggered") } />
  )
}

Now whenever you type something into the input box, React will trigger the function that we passed into the onChange prop.

Common use cases for React onChange handler

In regular HTML, form elements such as and usually maintain their own value:

<input id="name" type="text">

Which you can retrieve by using the document selector:

var name = document.getElementById("name").value;

In React however, it is encouraged for developers to store input values in the component’s state object. This way, React component that renders the form elements will also control what happens on subsequent user inputs. First, you create a state for the input:

import React, { useState } from "react"

function App(props) {
  const [name, setName] = useState('')

}

Then, you create an input element and call the setName function to update the name state. Every time the onChange event is triggered, React will pass the event argument into the function that you define inside the prop:

import React, { useState } from "react"

function App(props) {
  const [name, setName] = useState('')

  return (
    <input 
      type="text"
      name="firstName"
      onChange={ (event) => setName(event.target.value) }  />
  )
}

Finally, you use the value of name state and put it inside the input’s value prop:

return (
  <input 
    type="text"
    name="firstName"
    onChange={ (event) => setName(event.target.value) }  
    value={name} />
)

You can retrieve input value in event.target.value and input name in event.target.name. You can also separate the onChange handler into its own function.

The event object is commonly shortened as e

import React, { useState } from "react"

function App(props) {
  const [name, setName] = useState('')

  function handleChange(e) {
    setName(e.target.value);
  }

  return (
    <input 
      type="text"
      name="firstName" 
      onChange={ handleChange }  
      value={name} />
  )
}

This pattern of using React’s onChange event and the component state will encourage developers to use state as the “single source of truth”.

Instead of using Regular JavaScript to retrieve input values, you retrieve them from the state.

Level up your programming skills

I'm sending out an email once every Wednesday with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.