0
0
ReactDebug / FixBeginner · 3 min read

How to Handle onChange Event in React: Simple Fix and Best Practices

In React, handle the onChange event by passing a function that receives the event object and updates state using useState. This function should access event.target.value to get the input's current value and update the component's state accordingly.
🔍

Why This Happens

Many beginners try to handle the onChange event without updating the component's state properly or forget to pass the event parameter. This causes the input to not update or React to throw errors.

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

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

  // Incorrect: missing event parameter and not updating state
  function handleChange(event) {
    setText(event.target.value); // 'event' is now defined
  }

  return <input type="text" value={text} onChange={handleChange} />;
}

export default MyInput;
Output
ReferenceError: event is not defined
🔧

The Fix

Fix this by defining the event parameter in the handler function and updating the state with event.target.value. This ensures React knows the input value changed and re-renders the component.

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

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

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

  return <input type="text" value={text} onChange={handleChange} />;
}

export default MyInput;
Output
An input box that updates its value as you type
🛡️

Prevention

Always define the event parameter in your onChange handlers and use useState to keep input values controlled. Use linting tools like ESLint with React rules to catch missing parameters. Prefer arrow functions for concise handlers and keep your components controlled for predictable behavior.

⚠️

Related Errors

Other common mistakes include:

  • Not setting the value prop on inputs, causing uncontrolled inputs.
  • Using onChange but forgetting to update state, so input appears frozen.
  • Trying to update state directly without using setState or useState setter.

Key Takeaways

Always pass the event parameter to your onChange handler function.
Use event.target.value to get the current input value inside the handler.
Update component state with useState setter to reflect input changes.
Keep inputs controlled by setting their value from state.
Use linting tools to catch common React event handling mistakes early.