Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
171
rated 0 times [  176] [ 5]  / answers: 1 / hits: 185598  / 9 Years ago, tue, january 19, 2016, 12:00:00

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?


More From » reactjs

 Answers
119

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 />;
}
}

[#63656] Sunday, January 17, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ravenl

Total Points: 338
Total Questions: 107
Total Answers: 112

Location: Belize
Member since Mon, Jun 20, 2022
2 Years ago
ravenl questions
Thu, Feb 18, 21, 00:00, 3 Years ago
Tue, Jan 12, 21, 00:00, 3 Years ago
Tue, Mar 17, 20, 00:00, 4 Years ago
;