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:
import React from 'react';
const ParentComponent = () => {
const handleClick = () => {
console.log('Button clicked!');
}
return (
<ChildComponent handleClick={handleClick} />
);
}
export default ParentComponent;
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.