How to Pass Event Handlers as React.js Props
When working with React.js, you may often need to pass event handlers as props from a parent component to a child component. This can be useful for handling user interactions such as clicks, changes, or submissions.
Here’s how you can do it:
- Create the parent component with the event handler function.
- Pass the event handler function as a prop to the child component.
- Use the event handler function in the child component.
Step 1: Create the Parent Component
First, you need to create the parent component and define the event handler function. For example, you can create a parent component called “Parent” and define an event handler function called “handleClick”:
import React from 'react';
function Parent() {
function handleClick() {
console.log('Button clicked!');
}
return (
<Child handleClick={handleClick} />
);
}
Step 2: Pass the Event Handler Function as a Prop
Next, you need to pass the event handler function as a prop to the child component. In this example, we are passing the “handleClick” function to the “Child” component as a prop called “handleClick”:
import React from 'react';
function Child({ handleClick }) {
return (
<button onClick={handleClick}>Click me</button>
);
}
Step 3: Use the Event Handler Function in the Child Component
Finally, you can use the event handler function in the child component to handle user interactions. In this example, we are using the “handleClick” function as the onClick event for a button:
Now, when the button is clicked, the “handleClick” function from the parent component will be called, and the message “Button clicked!” will be logged to the console.
And that’s how you can pass event handlers as props in React.js! By following these steps, you can easily handle user interactions and manage state across your components in a clean and efficient way.