Categories
React Answers

How to create custom functions in a React component?

Spread the love

Sometimes, we want to create custom functions in a React component.

In this article, we’ll look at how to create custom functions in a React component.

How to create custom functions in a React component?

To create custom functions in a React component, we just add them into the component class.

For instance, we write

export default class Archive extends React.Component {
  saySomething(something) {
    console.log(something);
  }

  handleClick(e) {
    this.saySomething("element clicked");
  }

  componentDidMount() {
    this.saySomething("component did mount");
  }

  render() {
    return <button onClick={this.handleClick.bind(this)} value="Click me" />;
  }
}

to add the saySomething and handleClick methods into the Archive component.

Conclusion

To create custom functions in a React component, we just add them into the component class.

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 *