Categories
React Answers

How to Create a Custom Function in a React Component ?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *