Creating Reusable Helper Functions in React.js

React Create & Use Helper Functions | React Component

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

In the blow example, we have to create a helper class and use to it.
As an Example,

-  Helpers.js
  export function plus(xy) {
    return x + y;
  }

  export function minus(xy) {
    return x - y;
  }

  export function multiply(xy) {
    return x * y;
  }

  export function divide(xy) {
    return x / y;
  }

Import and Use of Helper methods in calculator components,

import React from 'react';
import { plusminus } from './Helpers'

class CalculatorComponents extends React.Component {
    constructor(props){
        super(props);
        this.yourClickFunction=this.yourClickFunction.bind(this);
    }

    yourClickFunction(xy){
      console.log(plus(xy)); //Output will be (10, 20) => 30
      console.log(minus(xy)); //Output will be (10, 20) => -10
    }

    render() {
        return (
            <div>
                <h4>React Helper functions</h4>
                <button onClick={this.yourClickFunction(1020)}>Click..</button>
            </div>
        );
    }
}
export default CalculatorComponents;


The result of these helper’s methods –

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

www.code-sample.com/. Powered by Blogger.
^