Back to: ReactJS Tutorials
Organizing Component Files in React:
In this article, I am going to discuss Organizing Component Files in React with Examples. In the previous article, we learned about JSX and how it looks, and why we add React imports. In this article, we will discuss organizing the files. We have a couple of components and therefore we can store them like,
But as our project grows and we will have more and more components, we might want to organize them into subfolders and not just throw them all into one components folder. And this is something we can already start with.
Here, we can argue that we have some general UI components, and some general user interface elements, which are not tied to a specific feature of the app. And then, we got some features-specific components, like ExpenseDate.js, ExpenseItem.js, and Expenses.js components, which are dealing with rendering expenses and expense data. And, therefore, in the components subfolder, we can create an Expenses subfolder and next to that a UI subfolder for general user interface elements.
And now we can move the card files into the UI folder and the Expenses, ExpenseItem, and ExpenseDate files into the Expenses folder.
Now, you just want to make sure that you update all your imports like in Expenses.js, where we imported card,
we now, first of all, need to go up one level with two dots and then a slash (‘../’) and then dive into the UI folder and import card. We need to go up one level because Expenses is now in the Expenses folder, and we need to get out of that folder into the next folder to then dive into the UI folder, which is a sibling folder to the Expenses folder. We don’t need to update the other imports because these files are still in the same folder as Expenses.js. For ExpenseItem.js, we also need to update the card import,
For that, we have to dive into the UI folder and then import the card. And in App.js, we no longer import Expenses from components’ Expenses, instead we dive into components and then into the Expenses folder and there it’s the Expenses file, which you want to import from.
So, now, we can adjust these imports. And if you did that and save the project then it will run the same as before,
We’re just doing this to organize our files, to keep our components organized, and to make sure that they’re not all in one big folder. Ultimately, it’s up to you how you want to organize them. You should just organize them such that you and any team members you might be working with are comfortable working with these files. That’s the most important thing which matters.