0
0
ReactHow-ToBeginner · 3 min read

How to Use event.target.value in React: Simple Guide

In React, you use event.target.value inside an event handler to get the current value of an input element when a user types or changes it. This value is often used to update the component's state to reflect the input's content.
📐

Syntax

The event object is passed automatically to event handlers in React. event.target refers to the element that triggered the event, and event.target.value gives you the current value of that element, such as a text input.

Use it inside an event handler like onChange to read user input.

javascript
function handleChange(event) {
  const inputValue = event.target.value;
  // Use inputValue as needed
}
💻

Example

This example shows a React functional component with a text input. When you type, event.target.value is used to update the state and display the typed text below the input.

javascript
import React, { useState } from 'react';

function TextInput() {
  const [text, setText] = useState('');

  function handleChange(event) {
    setText(event.target.value);
  }

  return (
    <div>
      <label htmlFor="input">Type something:</label>
      <input
        id="input"
        type="text"
        value={text}
        onChange={handleChange}
        aria-label="Text input"
      />
      <p>You typed: {text}</p>
    </div>
  );
}

export default TextInput;
Output
A text input box labeled 'Type something:' where typed text appears below as 'You typed: [your input]'.
⚠️

Common Pitfalls

  • Not using event.target.value inside the event handler: Forgetting to access value leads to no input reading.
  • Not updating state correctly: If you don't update state with the new value, the input won't reflect changes.
  • Using event.target.value outside event handlers: The event object is only valid during the event, so accessing it asynchronously can cause errors.
javascript
/* Wrong way: Not using event.target.value */
function handleChange(event) {
  // Missing value extraction
  setText(); // No value passed
}

/* Right way: Using event.target.value */
function handleChange(event) {
  setText(event.target.value);
}
📊

Quick Reference

Remember these points when using event.target.value in React:

  • Use inside event handlers like onChange.
  • event.target is the element triggering the event.
  • value is the current content of input, textarea, or select.
  • Update component state to reflect changes.
  • Do not use event.target.value asynchronously outside the event handler.

Key Takeaways

Use event.target.value inside event handlers to get current input values.
Always update React state with event.target.value to keep UI in sync.
Access event.target.value only during the event to avoid errors.
Use onChange event for input elements to capture user typing.
event.target.value works with inputs, textareas, and selects.