Pass function as props in React | React JS
When working with React components, it is common to pass functions as props to child components. This allows the child components to communicate with the parent component and update the state of the application.
In React, you can pass a function as a prop to a child component by defining the function in the parent component and then passing it as a prop to the child component.
Here is an example of how to pass a function as a prop in React:
// ParentComponent.js
import React from 'react';
import ChildComponent from './ChildComponent';
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
this.incrementCount = this.incrementCount.bind(this);
}
incrementCount() {
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div>
<ChildComponent increment={this.incrementCount} />
</div>
);
}
}
export default ParentComponent;
// ChildComponent.js
import React from 'react';
class ChildComponent extends React.Component {
render() {
return (
<div>
<button onClick={this.props.increment}>Increment</button>
</div>
);
}
}
export default ChildComponent;
In this example, the ParentComponent
has a state property count
and a function incrementCount
that updates the state. The incrementCount
function is passed as a prop to the ChildComponent
using the increment
prop. When the button in the ChildComponent
is clicked, it calls the increment
function that was passed as a prop from the parent component.
Passing functions as props in React is a powerful feature that allows for easy communication between parent and child components. It is a common pattern in React development and is often used to create dynamic and interactive user interfaces.