DEV Community

Anil Singh
Anil Singh

Posted on • Updated on

Create & Use Helper Functions | React Component

You can use helper functions just like other frameworks. Also, you can achieve code reusability by using these functions.

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

As an Example,

Helpers.js

plus(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(this.plus(x, y)); //Output will be (10, 20) => 30
    }

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

Explore React 63 Best FAQs
https://www.code-sample.com/2018/03/reactjs-interview-questions-and-answers.html

Top comments (5)

Collapse
 
dance2die profile image
Sung M. Kim

Hi Anil,

Could you format/highlight code snippets referring to the Editor Guide?

Collapse
 
anilsingh profile image
Anil Singh

Actually, I am new here. wen I get time i will try to do the same.

Collapse
 
dance2die profile image
Sung M. Kim

Sounds good. and I hope my suggestion didn't deter you from posting at all :)

Collapse
 
alsmith808 profile image
Alan Smith

'In the blow example'

Steady on now, this is a family website!!!

Collapse
 
benson338 profile image
BMK • Edited

why plus() doesn't needs to be called this.plus() unlike some other functions..?