DEV Community

Anil Singh
Anil Singh

Posted on • Edited on

4 1

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

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..?

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay