Tip 49: Build Applications with Component Architecture
Do you arrange code by file type? What about when CSS is tied to a single HTML file? Do you keep them in different directories but with similar file names?
For a long time, developers would keep files separated by type. The root directory would contain a css directory, a js directory, an img directory, and so on.
The problem was that the pieces aren’t really separate concerns. Except for a few global styles, CSS is built to work with specific markup. What happens when that markup is removed? If you have disciplined developers, they’d remove the relevant CSS. But most of the time, it stayed. It was never used—it just took up space.
As developer tools improved, a new pattern emerged. The new pattern is component architecture. A component is the combination of all relevant code into a single directory. You then build a web page or application by adding pieces one at a time—a button is in a sidebar, which is in a page—until you have your working application.
Component architecture isn’t without problems. The biggest problem with component architecture is that it depends on build tools and, to a lesser extent, frameworks. In this tip, you’ll be working with React code. You’re going to use scaffolding developed by create-react-app. This means you don’t have to worry about setting up the build system. You’ll explore that a little in the next tip.
It’s important to understand, however, that component architecture is not React specific. You can apply the idea in a variety of frameworks. Cody Lindley wrote a great article on the subject. Still, a framework saves some of the trouble of laying a foundation.
To see component architecture at work, build a basic component: a copyright statement. A copyright statement contains the current year, a declaration of copyright, and some styling. With component architecture, you combine everything into a simple package. Here’s an example: