DEV Community

SnoopyDev
SnoopyDev

Posted on • Updated on

Make it work first, split after. Creating components without pain in React

Create components for your React app is one of the most extensive work you do when coding. Export, import, use props, check many components files at the same time, handle data, functions and so on.

If you're starting creating multiple component files at once and keeps opening them at the same time, you're punishing yourself unnecessarily.

These three points should be your mantra:

1- Have one single block of code and work on it until it works as you expect. So, implement functions, variables, hooks, libs, styles and all you need.

2- Identify the parts of the code that make sense to be a single component. (You can use the Athomic Design methodology to do it:
Read Atomic Design

3- Do not "over-split" your code.

Make it work first.

Before you think about create splitted components, you should focus on make the whole thing work.

I saw many devs creating components without even have clarity what props they should pass trough them and what should be a separate component or not, turning a simple task into a painful activity.

I'll show you what should be the best way to create components in React. (You can use this methodology with other frameworks)

I'll use a simple HTML table as example to make it easy for anyone.

Our main component file:

Image description

As you see above, we have a complete table with it's childrens (headers and rows), but what if we want to split it into small components?

We'll do not create any file now, we'll just focus on make everthing works as we expect.

Check the example below:

Image description

Now we have our small parts of our table separated on components but they're still on the same file, so we can debug and test our code with ease, without worry about imports and work with multiple files.

Let's finish our example, implementing our functions, props and data:

Image description

As you can see, now we have everything we need, so we can just create our component files and export the small parts of our table, import it on our main componet, and everything will work as it have been before the split.

Check it out:

Image description

--
If you like these types of article, do not forget to like, comment and follow me. This will give me the feedback I need to keep posting.

Top comments (0)