How to use Helper functions in a React component?
Create a helper function is a very common practice to achieve modularity. However, you can use it for code reusability.
You can use Helper Functions just like other frameworks. Also, you can achieve code reusability by using these functions.
Explore React 63 Best FAQs
Explore React 63 Best FAQs
In the blow example, we have to create a helper class and use to it.
As an Example,
As an Example,
- Helpers.js
export function plus(x, y) {
return x + y;
}
export function minus(x, y) {
return x - y;
}
export function multiply(x, y) {
return x * y;
}
export function divide(x, y) {
return x / y;
}
Import and Use of Helper methods in calculator components,
import React from 'react';
import { plus, minus } from './Helpers'
class CalculatorComponents extends React.Component {
constructor(props){
super(props);
this.yourClickFunction=this.yourClickFunction.bind(this);
}
yourClickFunction(x, y){
console.log(plus(x, y)); //Output will be (10, 20) => 30
console.log(minus(x, y)); //Output will be (10, 20) => -10
}
render() {
return (
div>
h4>React Helper functionsh4>
button onClick={this.yourClickFunction(10, 20)}>Click..button>
div>
);
}
}
export default CalculatorComponents;
The result of these helper’s methods –