Nick Pineda
Nick Pineda

Reputation: 6462

ReactJs Global Helper Functions

Issue: I have a lot of small helper functions that don't necessarily need to live in a component(or maybe they can but they will make that component bloated with a lot of code).My lazy side just wants to just let those all just be some sort of global functions that the components can call.I really want to make good ReactJs code.

Question: What are the best practices in terms of global helper functions in Reactjs? Should I force them into some sort of component or just shove them into the other components?

Basic Example:

function helperfunction1(a, b) {
    //does some work
    return someValue;
}

function helperfunction2(c, d) {
    //does some work
    return someOtherValue;
}

function helperfunction3(e, f) {
    //does some work
    return anotherValue;
}

function helperfunction4(a, c) {
    //does some work
    return someValueAgain;
}


var SomeComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

var SomeOtherComponent =
    React.createClass({

        //Has bunch of methods

        //Uses some helper functions

        render: function () {

        }

    });

Upvotes: 52

Views: 63833

Answers (6)

Pierce
Pierce

Reputation: 1

react can be avoided altogether, like Michiel says though a slight improvement would be to put all those pure js functions in a single fle then connect it to your html start page and the functions will be available everywhere:

just with a

<script src='./global-func.js' ></script>

its a dirty hack but it works ;)

you wont have to import the file into every component class you make

Upvotes: 0

Akshay K Nair
Akshay K Nair

Reputation: 1476

Use a React context to do something like this. It's built for this exact use case; Doc: https://reactjs.org/docs/context.html

Upvotes: 1

curv
curv

Reputation: 3854

Just another option, if you don't want to split into a separate module, you could create a private method in your parent component like below and use freely within this component or pass to the child components via props..

var YourComponent = React.createClass({

    globalConfig: function() {
        return {
            testFunc: function () {
                console.log('testing...');
            },
        };
    }(),

    ......
    render: function() {
        this.globalConfig.testFunc(); // use directly

        <ChildComponent testFunc={this.globalConfig.testFunc} /> // pass to child
    .....

All untested, but that's the idea...

Upvotes: 1

Michiel
Michiel

Reputation: 2203

You can export multiple functions from a file, no React needed per se:

Helpers.js:

export function plus(a, b) {
  return a + b;
}

export function minus(a, b) {
  return a - b;
}

export function multiply(a, b) {
  return a * b;
}

export function divide(a, b) {
  return a / b;
}

You can then import the functions you need:

import { multiply, divide } from './Helpers'

Upvotes: 61

Sebastien Lorber
Sebastien Lorber

Reputation: 92220

You can use a module-bundling tool like Webpack or Browserify for that. Put your reusable functions in a CommonJS module.

Do not use Mixins, they will probably be deprecated in next versions of React as there's no standard way to declare mixins in React with ES6 syntax and they prefer to wait for ES7 that will probably standardize mixins. And there's no point coupling your reusable code to React unless it uses React lifecycle's methods.

Upvotes: 9

wilson
wilson

Reputation: 11

You can use modulejs. or you can use mixins (https://facebook.github.io/react/docs/reusable-components.html#mixins)

Sample for mixins: https://jsfiddle.net/q88yzups/1/

var MyCommonFunc = {
    helperFunction1: function() {
       alert('herper function1');
    },
    doSomething: function(){
        alert('dosomething');
    }
}

var Hello = React.createClass({
    mixins: [MyCommonFunc],
    render: function() {
        this.doSomething();
        return <div onClick={this.helperFunction1}>Hello {this.props.name} </div>;
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));

Upvotes: 1

Related Questions