Write clean and maintainable code
We all have come through posts where people show off how to write cool stuff in the backend/server-side in languages like C#, nodeJs, java, javascript, etc. Today let us understand, it is also absolutely necessary to structure your front-end side clean and nice as well. So let’s get started.
Recently I came across a certain area in application example navigation bar, where there is a lot of sub-menus which need to be shown. An example would be like this
If you look at the menu items from a front end or developer’s brain, it can be summarized as
- It is just a list of menu items
- Has a name
- Has an icon
- It should redirect to subpage or URL
- Displayed in an unordered list
So usually we would write HTML template to render the above image like this
<div class="side-bar">
<ul>
<li class="side-bar-item">
<a routerLink="/mail" class="nav-link">
<i class="fa fa-mail"></i>
</a>
</li>
<li class="side-bar-item">
<a routerLink="/char" class="nav-link">
<i class="fa fa-char"></i>
</a>
</li>
</ul>
</div>
So the li is repeated multiple times with an appropriate class and the name of the item. Let’s say during development we keep adding menu items. But in a long span, it becomes redundant and there will be 500 lines just for the sidebar. So how do we improve it?
The Art of writing clean code brain kicks in
The for loop that you studied in your university must be kicking in your head. You can iterate over a list of items, because since its sidebar and the menu’s will be known values, so you can always iterate and display them.
We are in the 21st century. Any javascript framework that you use, be it Angular / Vue / React, it has a way to iterate objects and render them in the HTML template. So i re-wrote the above code like this. This below snippet is from for Angular applications.
<div class="side-bar">
<ul>
<li *ngFor="let menu of subMenuItems"
[routerLinkActive]="['active']"
class="nav-item">
<a routerLink="{{menu.routerLink}}"
class="nav-link">
<i class="{{menu.icon}}"></i>
{{menu.name}}
</a>
</li>
</ul>
</div>
So this looks much cleaner, and you will never have to touch the HTML to add new menu item. So how’d you do it? Open your respective HTML helper, in the angular side it is typescript, so if you react it must be javascript. All you need to do is create an array like this.
mySubMenu = [
{name:'Mail',icon:'fa fa-mail',routerLink:'/mail'},
{name:'Chat',icon:'fa fa-chat',routerLink:'/chat'},
{name:'Admin',icon:'fa fa-admin',routerLink:'/admin'}
]
Conclusion
I hope this helps you in writing much more awesome HTML templates. You might think oh wait, even my application has a lot of menu and submenu. Let me conclude this by saying a famous quote from Robert Baden-Powell.
Try and leave this world a little better than you found it, and when your turn comes to die, you can die happy in feeling that at any rate, you have not wasted your time but have done your best.