Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React structure for own utils files

Is there any best practice in structure React app? Sometimes, I need move universal functions to separate files. But, where? It's not a node_module.

  • .gitignore
  • .git
  • package.json
  • node_modules
  • src
    • components
    • views
    • reducers
    • actions
    • utils ← this is my utils folder.
      1. DateUtils.js
      2. StringUtils.js
      3. NumberUtils.js

The another way is create Base react component that will contain all utils. All another react files will be child of this component.

class MyBaseComponent extends React.Component {

    dateUtilsMethod() {
       ...
    }

    stringUtilsMethod(myString) {
        ...
    }

}

class MainPageView extends MyBaseComponent { ... }

What is the best solution?

like image 481
Vesmy Avatar asked Jan 30 '23 14:01

Vesmy


1 Answers

I think that you are on the right track, though it is arguable.
One thing that is missing in my opinion is an index file in the utils folder that exposes each util file via export.
for example:

//utils/index.js:  

 export { default as DateUtils} from './DateUtils';
 export { default as StringUtils} from './StringUtils';
 export { default as NumberUtils} from './NumberUtils';

And you will import them from other files like so:

import { DateUtils, NumberUtils} from '../utils ';

Or import all as alias:

import * as utils from '../utils ';
like image 63
Sagiv b.g Avatar answered Feb 03 '23 08:02

Sagiv b.g