Sometimes, we want to create a custom function in a React component.
In this article, we’ll look at how to create a custom function in a React component.
Creating a Custom Function in React Component
We can create a custom function within a React component.
For instance, we can write:
class App extends React.Component {
log(message) {
console.log(message);
}
handleClick(e) {
this.log("button clicked");
}
componentDidMount() {
this.log("component mounted");
}
render() {
return <button onClick={this.handleClick.bind(this)}>click me</button>;
}
}
We have the log
method that runs console.log
.
We can call it from other method with this.log
.
Conclusion
We can create a custom function within a React component.