How to pass functions as props in React?

To pass a function as a prop in React, you can simply define the function in the parent component and then pass it as a prop to the child component. Here is an example:

  1. In the parent component, define a function that you want to pass as a prop. For example:
import React from 'react'; const ParentComponent = () => { const handleClick = () => { console.log('Button clicked!'); } return ( <ChildComponent handleClick={handleClick} /> ); } export default ParentComponent;
  1. In the child component, access the function passed as a prop and use it as needed. For example:
import React from 'react'; const ChildComponent = (props) => { return ( <button onClick={props.handleClick}>Click me</button> ); } export default ChildComponent;

In this example, the handleClick function is defined in the ParentComponent and passed as a prop called handleClick to the ChildComponent. The ChildComponent then accesses the function through the props parameter and uses it as an onClick event handler for a button element.

By following this pattern, you can easily pass functions as props in React components.