Morado labs

Why Structure our React.js components?

June 23, 2023

React gives us a lot of flexibility with how we create our components. We are able to bunch as much logic as we want into them and as long as we return JSX they will work.

An important part of programming is the maintainability and readability of our code.

Because no program is perfect – we will run into bugs. By making these bugs easy to find and identify, we can squash them quicker and easier.

With our React components in particular, we can separate our component logic into several files to improve readability, testability and maintainability of our code.


The Structure:

We start by creating a folder for our component and our main component file will be an index.js file.

An example component may look like the following:

SomeComponent/ – Folder Name
index.js – Main component file
helpers.js – Local helper functions
schema.js – Local form schema
interface.ts – Interface File (if using TypeScript)
tests/test.js – Test folder with a test file for our component tests


Let’s break down each of these files:

index.js – Our index file will contain our core component. This will import from our other local files and export a component that we can then use within our application.

helpers.js – Our helpers file will contain logic and or data used in our component. If we have a large array that is used in our component, we can store it here.

This allows us to keep our components clean and short – while having our data close by in case we need to check it.

This also goes for the logic our component uses. Instead of bloating our component before the
return statement, put that logic into a function and import it from the helpers file.

schema.js – Often in React.js we use a library such as Yup to create our form schemas.

These take up a lot of lines of code and are not updated too often. Because of that – we can keep these in their own separate file.

Once again, we know where it lives, but it stays out of our way in the main component file.

interface.ts – When using TypeScript, we often create interfaces to validate the type of our props.

These can easily be stored separately as they only need to change when our props update.

tests/tests.js – When testing our component, it’s advisable to keep tests close to the component itself.



This methodology to create components allows one to keep an easy separation of concerns without too much extra effort.

Oftentimes when viewing a new component, we do not care about the nitty-gritty logic unless we have to.

By separating things early on, it allows us to quickly scan components to understand what they are doing, while having a structure in place where we can easily find the piece of code that we need.



Other articles

What is React.js

React.js is a JavaScript based library used to build user-interfaces (UI’s) on the web. It provides functionality that allows software developers to build interactive and

Read more »