LoginSignup
2
1

How to think in components using React

Last updated at Posted at 2023-11-30

At my company at Wevnal, many people that have not too much experience with React have asked me at some point how they can write better code for it, since they've stated that when they create the components, they look quite bloated and not very clean.

Since it seems to be a recurring problem with people starting with React, I'd like to address it to help them to shape the mind into a component-centric way.

Keep in mind that this guide is headed towards people that knows about programming but doesn't have too much experience with React. Also, this is not meant to teach about React (since there are lots of good tutorials on the web), but rather how to think on solutions in a React-efficient manner.

Introduction

As for myself, I started on frontend development in the middle days of jQuery, a library that despite being old and not very used today, it still finds a way to appear in one project or another, still enduring the pass of time.

For people that haven't heard about it, it's a library that back in the old days did very nice things for us developers:

  • Unified the way of programming across browsers
  • Made access to the DOM way easier

The way of using it was like any other library, in a procedural way much like we write Javascript code.

Then, when the first batch of modern frameworks appeared (in my case, with AngularJS), they came with a fresh mindset of "reactive components". That mean that, if used correctly, data would be "magically updated" inside them, allowing the developers to focus more on the domain solutions rather than DOM updating, etc.

From this point on, the mindset of "components" began to become mainstream. jQuery and equivalents began to feel so old school, but since the approach was quite different, it required to look at frontend projects from another perspective angle to get used to it and maximize their potential.

Components

The components are the key parts of any frontend framework. This terminology is not attached to only this technology, since they are a specifications to the web standards[1].

According to the React documents[2],
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation

What does this mean is that components should fulfill a specific use case, to not depend on other unrelated components, and they can be used anywhere the same use case are required.

In an essence, a component is not more than a function that executes code behind. They receive arguments and return values.

The important thing, is that anything can be a component. It's not limited to big functionalities, but anything that can be reused and have a specific purpose. Even, enclosing a <p> tag with a style class can be a component, if it's meant to be used in more than one place.

Components are meant to be composed to have more functionalities. That means that a component can contain inside, other components that serve smaller, more specific cases.

The act of thinking in components

The starting point

Let's put a simple example for this. Let's think about a simple but functionable web that we can analyze. And for this, Google Search's main page is the perfect example:

image.png

Before continuing, in how many components do the reader think that we can divide this page?

The problem is that the answer is, as many as you wish. And that's what it leads to people that doesn't work too often with frontend, to make them have components that look bloated and hard to read, because there's no golden rule of how it should be.

So, the minimum answer is: 1. Just having a <GoogleSearchPage /> component that would contain everything on the above image is enough to work, and the directorate would be happy and satisfied. But the inner programmer would say "I know we can do it better!", since we expect to be updated with more functions later.

For this example, each tag would correspond to a different component, and the inner tags would be the children of this component, also separate components. Each component should be on a separate file to maximise readability.

So, the first division would be like a standard web page: header, body, and footer.

image.png

<GoogleSearchPage>
    <Header/>
    <Body/>
    <Footer/>
</GoogleSearchPage>

This gives us a good separation on the general overview of the page, so we can put related things together.

The header

For the header, although there are 4 elements, they are a bit different:

  • The two first elements are standard navigation links
  • One element is a Google Apps menu
  • One is a Google Account menu

For the two first, usually navigation links are in a navigation container to format the links properly, so we can set a component for that. Then, each link also has its own design rules, so we can create a component for this, format it, and reuse it on both links.

For the menu items, the overlay is similar but its contents are different. Since they serve a similar functionality, we can make a menu component that on click it displays its children. The menu by itself is outside the scope of this document, but the general rules are the same.

Now, this items, should they be inside the navigation container? That's quite debatable, but for this case let's follow this rule: "they aren't navigation links, so they shouldn't be inside the navigation container".

So the components would look like this:
image.png

<GoogleSearchPage>
    <Header>
        <NavigationContainer>
            <NavigationLink />
            <NavigationLink />
        </NavigationContainer>
        <PopupMenu />
        <PopupMenu />
    </Header>
    <Body/>
    <Footer/>
</GoogleSearchPage>

The body

The header was quite straightforward, but the body is a bit more complex than that. Still, with the proper way of thinking, we can decompose it in the same way.

The first would be the logo. Here is where things become a little bit fuzzy, because this is just an image, with a little bit more code than just a <img src="logo.png" />. Then, should it be a component?

The answer, as always, depends on the project type. So the questions to answer are:

  • Is this going to be used elsewhere?
  • Is it complex enough to isolate it?
  • Does it have a meaning by itself?
  • Do we gain in readibility by making it a component?
  • Will it be easier to update if it's separated?

The main reason to move it as a component in this case, is reason number 3. In the body, it will be way easier to read <Logo /> than <img src="logo.png" />. And that just removes a burden in the brain for the poor maintainer.

The next thing would be the search functionality. This actually is composed of: the search input and the search buttons. So both should belong to a single component.

The search input is quite straightfoward, although it contains some icons and icon buttons. The icons can be separated as components, and also we can make buttons that contain these icons. Lastly, the text input seems simple, so should it be a component? We come across the same dilemma as before, but in this case, its self meaning isn't as strong as the logo, so for this time we won't make it a separate

Then, the buttons. Should they be a separate component? Although they don't have any specific functionality, the styling they carry makes them a good candidate. Then, should they be inside a separate container? Up to debate, but that makes it easier to handle in case more buttons are added, so why not?

Finally, the language text. This doesn't belong to the form at all, so it should be separated. Now, since this serves a self-contained purpose, a separated component will be good. The link seem to be used only here, so for this time let's keep it as it is.

So, the body separation would be like this:

image.png

<GoogleSearchPage>
    <Header>
        <NavigationContainer>
            <NavigationLink />
            <NavigationLink />
        </NavigationContainer>
        <PopupMenu />
        <PopupMenu />
    </Header>
    <Body>
        <Logo />
        <SearchForm>
            <SearchInput>
                <Icon />
                <IconButton>
                    <Icon />
                <IconButton>
                <IconButton>
                    <Icon />
                <IconButton>
            </SearchInput>
            <SearchButtons>
                <SearchButton />
                <SearchButton />
            </SearchButton>
        </SearchForm>
        <LanguageText />
    </Body>
    <Footer/>
</GoogleSearchPage>

The footer

Finally, the footer. We can see there are two rows of similar styling, so we can make that a component.
The first row only contains information about the location, so for now it's only a styled text without link. For the sake of this example, let's leave it as it is.
The second row contains a list of links. It has a similar structure about the header navigation links, so should we use the same? Again, this depends of the type of project and the objective of the bottom links. We cannot infer that much just with an image, so let's say that we can use the same. At least, if we need to replace it with its own style for example,

Then, it will become like this:
image.png

<GoogleSearchPage>
    <Header>
        <NavigationContainer>
            <NavigationLink />
            <NavigationLink />
        </NavigationContainer>
        <PopupMenu />
        <PopupMenu />
    </Header>
    <Body>
        <Logo />
        <SearchForm>
            <SearchInput>
                <Icon />
                <IconButton>
                    <Icon />
                <IconButton>
                <IconButton>
                    <Icon />
                <IconButton>
            </SearchInput>
            <SearchButtons>
                <SearchButton />
                <SearchButton />
            </SearchButton>
        </SearchForm>
        <LanguageText />
    </Body>
    <Footer>
        <FooterRow/>
        <FooterRow>
            <NavigationContainer>
                <NavigationLink />
                <NavigationLink />
                <NavigationLink />
                <NavigationLink />
                <NavigationLink />
                <NavigationLink />
                <NavigationLink />
            </NavigationContainer>
        </FooterRow>
    </Footer>
</GoogleSearchPage>

With this, we have concluded our training about how to componentize a page. Each part looks self-contained and reusable, and thus more maintainable in the future.

Conclusion

Separating into components is mainly a matter of semantics over the functionality of a page. There's no hard rule about what or when to make a component, so as long as the they make sense by themselves to be separated, then proceed to do so.
This would take some projects after you can begin to do it unconsciously, so at the beginning just follow your instinct when you say to yourself "I have the gut that this would be better as a separate component".

This is also not a definitive guide. For this page, there can be more components to make, or less if some parts are not required, or as requirements change in the future. Again, the only hard rule is that it has to make sense.

I hope this would be useful for people wanting to jump into frontend frameworks and help them to advance the path of clean and reusable code.

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1