How to Pass an onChange Event Handler to a Child Component in React?

Estimated read time 2 min read

Passing an onChange event handler to a child component in React is useful when we want to capture user input or changes to a component’s state in the parent component. Here’s an example:

Assuming we have a parent component called ParentComponent and a child component called ChildComponent, and we want to pass an onChange event handler from ParentComponent to ChildComponent, we can do it in the following way:

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

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

  const handleTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setText(event.target.value);
  }

  return (
    <div>
      <ChildComponent onTextChange={handleTextChange} />
      <p>Text: {text}</p>
    </div>
  );
}

In the code above, we define a state variable called text and an event handler called handleTextChange that updates the state variable when the user types something in an input field. Then, we pass the event handler as a prop called onTextChange to the ChildComponent component.

In the receiving component, we can access the onChange event handler using the props parameter. Here’s an example implementation of ChildComponent that uses the passed onTextChange prop:

import React from 'react';

type ChildComponentProps = {
  onTextChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

function ChildComponent(props: ChildComponentProps) {
  return (
    <div>
      <input type="text" onChange={props.onTextChange} />
    </div>
  );
}

export default ChildComponent;

In the ChildComponent component, we define the onTextChange prop using the type (event: React.ChangeEvent<HTMLInputElement>) => void. We can then use the passed event handler by attaching it to the onChange event of an input field, like <input type="text" onChange={props.onTextChange} />. When the user types something in the input field, the handleTextChange function in the parent component is called, updating the text state variable, which is then displayed on the screen.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply