This content originally appeared on DEV Community and was authored by Victor Ocnarescu
Is there a perfect file structure for React projects? Probably not. But some are far better than others.
Over the years I discovered that I tend to structure files in some specific ways, which I believe are easier to understand and reasonable.
Meaningful folder names
Naming things is one of the toughest things to get right in programming. One of my favorite tactics to naming folders is to extract the subject and use it:
- want a place for public resources? the
public
folder should be a good fit; - have some custom hooks that you are proud of? keep them easy to find in the
hooks
folder; - want to include yet another css file? store them in the
css
folder.
And so on and so forth.
Little to no folder nesting
I always wondered about the src
folder and why it exists. And to this day it still is one of the many mysteries of programming.
I like to keep all my folders as close to the project root as possible. This way, they can be discovered more easily by any new dev working on the project.
Avoiding too much nesting is also recommended by the official React documentation as well.
Grouping by feature
The components
folder is one of my exceptions: it has two (2) levels of nesting. Common components are accessible right from the folder root, while "specialized" components have they own folder.
The contents of the components
folder:
-
Button.jsx
- common button components -
Link.jsx
- common link component -
Forms
-
AddClientForm.jsx
- specific "form" component -
EditClientForm.jsx
- another specific "form" component
-
Minimal example
This is the project structure for a starter project I authored and for many projects I'm working on right now.
api
components
css
data
functions
hooks
models
pages
public
LICENSE
README.md
I hope the folder structure is self explanatory. If it is not, I have done a lousy job at naming folders. Let me know in the comment section below.
Closing thoughts
My favorite file structure:
- is easy to read and understand
- is shallow nested
- is grouped by features
Have a different opinion? Can't wait to hear it!
This content originally appeared on DEV Community and was authored by Victor Ocnarescu
Victor Ocnarescu | Sciencx (2021-08-20T10:30:05+00:00) Better file structure in React projects. Retrieved from https://www.scien.cx/2021/08/20/better-file-structure-in-react-projects/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.