Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 () {          }      }); 
like image 550
Nick Pineda Avatar asked May 13 '15 03:05

Nick Pineda


People also ask

What are helper functions in React?

One of the well known conventions of React components is that any logic should be broken out of the render function into a helper function. This keeps the component clean, and separates the concerns inside of the component.

How do I export all functions in React?

Use named exports to export multiple functions in React, e.g. export function A() {} and export function B() {} . The exported functions can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a single file.


1 Answers

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' 
like image 71
Michiel Avatar answered Sep 20 '22 17:09

Michiel