DEV Community

Discussion on: How do you structure your React projects?

Collapse
limxingzhi profile image
XING • Edited on

I split my UI components and Pages into separate folders.

Both are React components, but the Pages provide a skeleton template and access to global state. The React Router will only route to Page Components, reading and writing to global state or external APIs are done through the Page Component too.

I will then cascade down the global data down from my Page Components into my UI Components. This means my UI components do not have to access the global state or external APIs, making them more predictable and easier to test.

For each Page or UI Component, I will create a folder and contain jsx + style sheet (I use the BEM model over CSS-IN-JS) + unit testing in that folder like

  • /src/component/CardDetail/CardDetail.jsx
  • /src/component/CardDetail/CardDetail.sass
  • /src/page/LoadingPage/LoadingPage.jsx
  • /src/page/LoadingPage/LoadingPage.sass

I also have 2 index files that will help me to control whether I want to lazy load the components and clean up my imports/exports. I can wrap the page components with a HOC or React Children (the fancy name escapes me at the moment) and I can apply a standard page template at this place. This allows me to do things like having a standard prop to change document.title, or setting standardize page styles, or setting page title on the document through a prop, things like that.

You can try the cra-template-xz create-react-app template if you want to take a look.
npx create-react-app my-app --template cra-template-xz

It is a pretty common way to structure reacat applications I think.

Collapse
isarisariver profile image
Marian Author

Thanks for sharing, I'll check it out!