Change events on React form elements

January 17, 2021

Here you'll find code samples demonstrating how to retrieve the current value when the change event is triggered in textarea, select, and various input elements. Note that we get this value from event.target.value in all cases except for input[type="checkbox"], where we use event.target.checked to determine whether the checkbox is checked.

Textarea

<textarea
  onChange={(event)=> {
    console.log(`Value change on textarea: ${event.target.value}`);
  }}
/>

Select

<select
  onChange={(event)=> {
    console.log(`Value change on select: ${event.target.value}`);
  }}
>
  <option>Red</option>
  <option>Green</option>
  <option>Blue</option>
</select>

Input type="text"

<input
  type="text"
  onChange={(event)=> {
    console.log(`Value change on input: ${event.target.value}`);
  }}
/>

Input type="checkbox"

<input
  type="checkbox"
  onChange={(event)=> {
    console.log(`Value change on checkbox: ${event.target.checked}`);
  }}
/>

Input type="radio"

<>
  <label htmlFor="radio_a">Radio A</label>
  <input
    type="radio"
    name="radioExample"
    id="radio_a"
    value="A"
    onChange={(event)=> {
      console.log(`Value change on radio: ${event.target.value}`);
    }}
  />
  <label htmlFor="radio_b">Radio B</label>
  <input
    type="radio"
    name="radioExample"
    id="radio_b"
    value="B"
    onChange={(event)=> {
      console.log(`Value change on radio: ${event.target.value}`);
    }}
  />
</>

Input type="color"

<input
  type="color"
  onChange={(event)=> {
    console.log(`Value change on color: ${event.target.value}`);
  }}
/>

Input type="date"

<input
  type="date"
  onChange={(event)=> {
    console.log(`Value change on date: ${event.target.value}`);
  }}
/>

Input type="time"

<input
  type="time"
  onChange={(event)=> {
    console.log(`Value change on time: ${event.target.value}`);
  }}
/>

Input type="week"

<input
  type="week"
  onChange={(event)=> {
    console.log(`Value change on week: ${event.target.value}`);
  }}
/>

Input type="range"

<input
  type="range"
  min={0}
  max={100}
  step={10}
  onChange={(event)=> {
    console.log(`Value change on range: ${event.target.value}`);
  }}
/>

These examples demonstrate how to handle change events for different form elements in React. By logging event.target.value (or event.target.checked for checkboxes), you can easily capture and use the current value of the input in your application.