Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom function in React component

I have a React component

export default class Archive extends React.Component {     ... } 

componentDidMount and onClick methods partially use the same code, except for slight change in parameters.

Is it possible to create a function inside the component class so it can be reused in the scope of the component?

like image 242
Alexey Avatar asked Jan 19 '16 11:01

Alexey


People also ask

How do you write a function in React component?

We can create a functional component to React by writing a JavaScript function. These functions may or may not receive data as parameters. In the functional Components, the return value is the JSX code to render to the DOM tree. Example: Program to demonstrate the creation of functional components.

How do you make custom components in React?

1. Setup. First, create a new folder called, “CustomComponents,” then open your terminal and use the npx create-react-app command to create a quickly create a new React project called “custom-components.”

Can we create function inside function in React?

It is possible, but it is not a good solution at all. Yeah, it creates new function on each re-render, but it's not a case if you don't pass them as props.


2 Answers

You can create functions in react components. It is actually regular ES6 class which inherits from React.Component. Just be careful and bind it to the correct context in onClick event:

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" />;     } } 
like image 158
madox2 Avatar answered Sep 29 '22 06:09

madox2


Another way:

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} value="Click me" />;   } } 

In this format you don't need to use bind

like image 41
yiwen Avatar answered Sep 29 '22 06:09

yiwen