0

How to create a function file where I can code all my functions in just one single file and call it on my components. Like in PHP we create a function file and use require(function.php) where we code all the functions. I want to know how I can create such type of helper/function files for my project.

2 Answers2

0

In your react components

import specialFunctions from './specialFunctions'
...
specialfunctions.customFunction(something)

In your function file

//specialFuncions.js
const specialFunctions = () => {

  customFunction = (something) => { 
    ...
    return somethingElse
  }

  customFunction2 = (something) => { 
    ...
    return somethingElse
  }

  return {
    customFunction,
    customFunction2
  }
}
export default specialFunctions();
Mikaels Slava
  • 186
  • 2
  • 8
0

Inside js file for example helpers.js you declare function and add "export".

// helpers.js
export const counter = (a,b) => {
  const sum = a+b
  return sum
}

In file where you want to use counter function you import it.

// App.js

import { counter } from "./helpers.js"

const App = () => {
  ... 
  useEffect(()=>{
    counter(2,3)
  },[])
}

  return(
    <div>
    </div>
  )
Aga
  • 1,019
  • 1
  • 11
  • 16