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 () { } });
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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With