Back to: ReactJS Tutorials
Splitting Components into Multiple Components in React:
In this article, I am going to discuss Splitting Components into Multiple Components in React with Examples. Please read our previous article where we discussed Adding JavaScript Logic to React Components.
Why Split a React Component into Multiple Components?
As you work on your React application and on your React components, in any project, you will notice that your components eventually become bigger and bigger. As you have more and more logic and JSX code in them. It is something that would happen naturally. That is why React has this component concept. This allows you to split your application into smaller building blocks where every building block or every component is focused on one core task. And then you build your overall user interface by combining these building blocks. By doing that, you keep each component and its code base relatively small and manageable, and you can still build a complex user interface.
Can the Date Object be treated as a separate component?
Now, there is no hard rule for when to build a new component or add more to an existing component. But in our ExpenseItem component, we already see that it’s getting a little bit big. We could argue that the date object or the calendar-like item that we want to show on the user interface can be treated as a separate component. Of course, the same case could be made for the title or the amount, or the title and amount combined. As we said, there is no hard rule. But for the calendar, we have a couple of helper constants and extra styles.
So, we personally like to split this ExpenseItem component into two components, the ExpenseItem component which we already have, and a new component for rendering the date in the calendar item. And therefore, we have to create our second custom component.
Create another component for the Date object.
We are creating a new file in the components folder and we name it as ExpenseDate.js.
The file name is up to you but we recommend you follow this convention of naming, start with a capital character, one word and every extra word should also start with a capital character. The file name should also express what’s happening inside of that file or What would that component be about.
The ExpenseDate.js component will be about rendering the date of an expense. Now in there, we create a new component and that still is a function. Components in React are just regular functions with the extra twist of returning the JSX code. We named it as ExpenseDate, again, we’re following the convention that is to repeat the file name as the function name. And then we write the export statement to make it reusable outside of this file.
function ExpenseDate(){
}
export default ExpenseDate;
Now inside the function, we want to calculate month, day, and year. So, we cut the logic from ExpenseItem and move it to ExpenseDate as,
function ExpenseDate(data) { const month = data.date.toLocaleString("en-US", { month: "long" }); const year = data.date.getFullYear(); const day = data.date.toLocaleString("en-US", { day: "2-digit" }); }
As we are using an object ‘data’ that is the function parameter so we need to accept data as a parameter in the function. Now in ExpenseItem, we want to use this new component. But before we do that, I will grab the div that contains month, year, and day as,
Now we return the above selected JSX code in ExpenseDate.js,
Now, in ExpenseItem, we have to add an import statement,
import ExpenseDate from “./ExpenseDate”;
Because we’re looking in the same folder as the ExpenseItem.js file lives in. And now in ExpenseItem.js, where we previously had our JSX code for the date, we output this ExpenseDate component instead. And as a side note, if you have a component that has no content between the opening and closing tags,
<ExpenseDate></ExpenseDate>
you can also write it a little bit differently. You can write it as a self-closing element like,
<ExpenseDate />
And we could do the same in App.js with the ExpenseItem since it also has no content between the opening and closing tags. This is totally optional but it is quite common to do that if there is no content between the opening and closing tag.
Now, we’re using ExpenseDate in the ExpenseItem component.
We’re doing this to move some of the JSX code and JavaScript logic out of the ExpenseItem into a separate component. The ExpenseDate component is also reusable and we can use it anywhere in this React application, not just in ExpenseItem. And it also helps us to keep ExpenseItem lean. It is easier to maintain and manage. The bigger your application gets and the more your components become, the more you want to look into splitting them up. There is no hard rule on when to split. This is something which will come with experience and you’ll also see plenty of examples throughout this course.
Now, we must not forget that our new ExpenseDate component needs a prop. It needs the date prop. Hence in ExpenseItem where we used ExpenseDate, we should set the date prop as.
Here, we have passed props.date as a value in the ExpenseDate component. Here it could be a little bit confusing because now we’re basically funneling some data through multiple levels of components. We can see the component tree,
Because now we don’t have just the App component or one other custom component, but we have multiple custom components and they are nested inside of each other. Just to make this really clear again, in the App component, we’re using the ExpenseItem component, and inside the ExpenseItem component, we’re using the ExpenseDate component. And not just that, we’re also forwarding our data with the help of props through multiple components. We are passing data from the App component into ExpenseItem and in ExpenseItem, we are outputting some of the data. But other parts of the data, the date, which we have already received through props, it’s then forwarded even further into the ExpenseDate component, again, by using props. Because props are our way of passing data from component A to B. And it’s also totally fine to have a component that just passes data around.
So, in the end, you could say, we pass data from App to ExpenseDate, and the date, is passed on. And we passed it on through ExpenseItem because that’s how props work. We pass data from a component to a direct child component. So, to a component that is used in another component’s JSX code and we can’t skip such component.
Since we use ExpenseDate inside of ExpenseItem, first of all, we have to pass that data to ExpenseItem and then forward it to ExpenseDate. We hope this is clear now. If it’s not entirely clear yet, you will be going to see this in detail and in many examples throughout the course. But with that, we are forwarding the date and we get this separate component now. If we now saved that all,
We can see that our date data being output here. Now we also want to have some styling and therefore we’ll add a new file, the ExpenseDate.css file,
You will find the complete code of the ExpenseDate.css file at the end of the article. After creating the ExpenseDate.css file, you can go to the ExpenseDate.js file and at the very top of that file write,
import “./ExpenseDate.css”;
Then we add the CSS classes name that is defined in ExpenseDate.css to the div element as,
<div className=”expense-date”>
<div className=”expense-date__month”>{month}</div>
<div className=”expense-date__year”>{year}</div>
<div className=”expense-date__day”>{day}</div>
</div>
If we save everything,
Now, we got this nice look here for our dates. And this looks much nicer. And we also practiced how we can add another component. And adding this component was optional, we can have put the entire JSX code which we have in a separate component now, into ExpenseItem. We can also add the ExpenseDate.css code to the ExpenseItem.css code. But then this ExpenseItem component would become bigger and bigger.
It is generally a good practice to keep your components small and focused. Below are the complete codes for all the files that we have used in this article.
ExpenseItem.js:
import ExpenseDate from "./ExpenseDate"; import "./ExpenseItem.css"; function ExpenseItem(data) { return ( <div className="expense-item"> <ExpenseDate date={data.date}/> <div className="expense-item__description"> <h2>{data.title}</h2> <div className="expense-item__price">₹{data.amount}</div> </div> </div> ); } export default ExpenseItem;
ExpenseDate.js:
import "./ExpenseDate.css"; function ExpenseDate(data) { const month = data.date.toLocaleString("en-US", { month: "long" }); const year = data.date.getFullYear(); const day = data.date.toLocaleString("en-US", { day: "2-digit" }); return ( <div className="expense-date"> <div className="expense-date__month">{month}</div> <div className="expense-date__year">{year}</div> <div className="expense-date__day">{day}</div> </div> ); } export default ExpenseDate;
ExpenseDate.css:
.expense-date { display: flex; flex-direction: column; width: 5.5rem; height: 5.5rem; border: 1px solid #ececec; background-color: #2a2a2a; color: white; border-radius: 12px; align-items: center; justify-content: center; } .expense-date__month { font-size: 0.75rem; font-weight: bold; } .expense-date__year { font-size: 0.75rem; } .expense-date__day { font-size: 1.5rem; font-weight: bold; }
App.js:
import ExpenseItem from "./components/ExpenseItem"; function App() { const expenses = [ { title: "Household Expense", amount: 25000, date: new Date(2023, 4, 27) }, { title: "Travel Expense", amount: 1300, date: new Date(2023, 5, 28) }, { title: "Education fees", amount: 5000, date: new Date(2023, 6, 29) }, ]; return ( <div> <h2>Hello Coders!</h2> <ExpenseItem title={expenses[0].title} amount={expenses[0].amount} date={expenses[0].date} /> <ExpenseItem title={expenses[1].title} amount={expenses[1].amount} date={expenses[1].date} /> <ExpenseItem title={expenses[2].title} amount={expenses[2].amount} date={expenses[2].date} /> </div> ); } export default App;
In this article, I am going to discuss the Concept of Composition in React with Examples. Here, in this article, I try to explain Splitting Components into Multiple Components in React with Examples. I hope you enjoy this Splitting Components into Multiple Components in React article.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.