Passing Events as Props in React

Passing Events as Props in React

In React, you can pass event handler functions as props to child components, allowing the parent to control the child's behavior.

Why Pass Events as Props?

- Allows better state management in the parent component.
- Enables reusable and modular components.
- Keeps event logic centralized.

Example Code

    
// Parent Component
function ParentComponent() {
  const handleClick = () => {
    alert("Button Clicked from Child!");
  };
  return ;
}

// Child Component
function ChildComponent({ onButtonClick }) {
  return ;
}
    
  

Best Practices

- Name event props clearly (e.g., onButtonClick, onInputChange).
- Keep event handling logic inside the parent component when necessary.
- Avoid unnecessary re-renders by using React's useCallback when needed.

Interactive Example