search
HomeWeb Front-endCSS TutorialNot Everything Needs a Component

Not Everything Needs a Component

Nov 26, 2024 am 03:32 AM

Not Everything Needs a Component

In the early 2000s, a new term, Divitis, was coined to refer to The practice of authoring web-page code with many div elements in place of meaningful semantic HTML elements. This was part of an effort to increase awareness of semantics in HTML within the frame of the Progressive Enhancement technique.

Fast forward 20 years - I witness a new syndrome affecting web developers, one I call componentitis. Here is my made-up definition:

Componentitis: the practice of creating a component for every aspect of a UI in place of a simpler and more reusable solution.

Components

So, first of all, what is a component? I think React popularized the term to refer to its building blocks:

React lets you combine your markup, CSS, and JavaScript into custom "components", reusable UI elements for your app.
React documentation - Your First Component

While the concept of reusable UI elements wasn’t new at the time (in CSS, we already had techniques like OOCSS, SMACSS, and BEM), the key difference is its original approach to the location of markup, style, and interaction. With React components (and all the subsequent UI libraries), it’s possible to co-locate everything in a single file within the boundaries of a component.

So, using Facebook’s latest CSS library Stylex, you could write:

import * as stylex from "@stylexjs/stylex";
import { useState } from "react";

// styles
const styles = stylex.create({
    base: {
        fontSize: 16,
        lineHeight: 1.5,
        color: "#000",
    },
});

export function Toggle() {
    // interactions
    const [toggle, setToggle] = useState(false);
    const onClick = () => setToggle((t) => !t);

    // markup
    return (
        <button type="button" onclick="{onClick}">
            {toggle}
        </button>
    );
}

You can be a fan or not of writing CSS in object notation (I’m not), but this level of co-location is often a good way to make a component-based project more maintainable: everything is within reach and explicitly bound.

In libraries like Svelte, the co-location is even more clear (and the code more concise):

<script>
    let toggle = $state(false)
    const onclick = () => toggle = !toggle
</script>

<button type="button">
    {toggle}
</button>

<style>
button {
    font-size: 16px;
    line-height: 1.5;
    color: #000;
}
</style> 

Over time, this pattern has gained so much traction to the point that everything is encapsulated in components. You have probably encountered page components like this:

export function Page() {
    return (
        <layout>
            <header nav="{<Nav"></header>} />
            
                <stack spacing="{2}">
                    <item>Item 1</item>
                    <item>Item 2</item>
                    <item>Item 3</item>
                </stack>
            
            <footer></footer>
        </layout>
    );
}

Co-location of one

The above code looks clean and consistent: we use the component interface to describe a page.

But then, let’s look at the possible implementation of Stack. This component is usually a wrapper to ensure all direct child elements are vertically stacked and evenly spaced:

import * as stylex from "@stylexjs/stylex";
import type { PropsWithChildren } from "react";

const styles = stylex.create({
    root: {
        display: "flex",
        flexDirection: "column",
    },
    spacing: (value) => ({
        rowGap: value * 16,
    }),
});

export function Stack({
    spacing = 0,
    children,
}: PropsWithChildren) {
    return (
        <div styles.spacing>
            {children}
        </div>
    );
}

We only define the styles and the root element of the component.

In this case, we could even say that the only thing we are co-locating is the style block since the HTML is only used to hold a CSS class reference, and there is no interactivity or business logic.

The (avoidable) cost of flexibility

Now, what if we want to be able to render the root element as a section and maybe add some attributes? We need to enter the realm of polymorphic components. In React and with TypeScript this might end up being something like the following:

import * as stylex from "@stylexjs/stylex";
import { useState } from "react";

// styles
const styles = stylex.create({
    base: {
        fontSize: 16,
        lineHeight: 1.5,
        color: "#000",
    },
});

export function Toggle() {
    // interactions
    const [toggle, setToggle] = useState(false);
    const onClick = () => setToggle((t) => !t);

    // markup
    return (
        <button type="button" onclick="{onClick}">
            {toggle}
        </button>
    );
}

In my opinion, this isn't very readable at first glance. And remember: we are just rendering an element with 3 CSS declarations.

Back to the basics

A while back, I was working on a pet project in Angular. Being used to thinking in components, I reached out to them to create a Stack. It turns out that in Angular polymorphic components are even more complex to create.

I started to question my implementation design and then I had an epiphany: why spend time and lines of code on complex implementations when the solution had been right in front of me all along?

<script>
    let toggle = $state(false)
    const onclick = () => toggle = !toggle
</script>

<button type="button">
    {toggle}
</button>

<style>
button {
    font-size: 16px;
    line-height: 1.5;
    color: #000;
}
</style> 

Really, that’s the barebone native implementation of the Stack . Once you load the CSS in the layout, it can be used right away in your code:

export function Page() {
    return (
        <layout>
            <header nav="{<Nav"></header>} />
            
                <stack spacing="{2}">
                    <item>Item 1</item>
                    <item>Item 2</item>
                    <item>Item 3</item>
                </stack>
            
            <footer></footer>
        </layout>
    );
}

Add type-safety in JavaScript frameworks

The CSS-only solution provides neither typing nor IDE auto-completion.

Also, if we are not using spacing variants, it might feel too verbose to write both a class and a style attribute instead of a spacing prop. Assuming you're using React, you could leverage JSX and create a utility function:

import * as stylex from "@stylexjs/stylex";
import type { PropsWithChildren } from "react";

const styles = stylex.create({
    root: {
        display: "flex",
        flexDirection: "column",
    },
    spacing: (value) => ({
        rowGap: value * 16,
    }),
});

export function Stack({
    spacing = 0,
    children,
}: PropsWithChildren) {
    return (
        <div styles.spacing>
            {children}
        </div>
    );
}

Note that React TypeScript doesn’t allow unknown CSS properties. I used a type assertion for brevity, but you should choose a more robust solution.

If you’re using variants you can modify the utility function to provide a developer experience similar to PandaCSS patterns:

import * as stylex from "@stylexjs/stylex";

type PolymorphicComponentProps<t extends react.elementtype> = {
    as?: T;
    children?: React.ReactNode;
    spacing?: number;
} & React.ComponentPropsWithoutRef<t>;

const styles = stylex.create({
    root: {
        display: "flex",
        flexDirection: "column",
    },
    spacing: (value) => ({
        rowGap: value * 16,
    }),
});

export function Stack<t extends react.elementtype="div">({
    as,
    spacing = 1,
    children,
    ...props
}: PolymorphicComponentProps<t>) {
    const Component = as || "div";
    return (
        <component styles.spacing>
            {children}
        </component>
    );
}
</t></t></t></t>

Prevent code duplication and hardcoded values

Some of you might have noticed that, in the last example, I hardcoded the expected values of spacing in both the CSS and the utility files. If a value is removed or added, this might be an issue because we must keep the two files in sync.

If you’re building a library, automated visual regression tests will probably catch this kind of issue. Anyway, if it still bothers you, a solution might be to reach for CSS Modules and either use typed-css-modules or throw a runtime error for unsupported values:

<div>





<pre class="brush:php;toolbar:false">.stack {
  --s: 0;
    display: flex;
    flex-direction: column;
    row-gap: calc(var(--s) * 16px);
}
export function Page() {
    return (
        <layout>
            <header nav="{<Nav"></header>} />
            
                <div classname="stack">



<p>Let's see the main advantages of this approach:</p>

<ul>
<li>reusability</li>
<li>reduced complexity</li>
<li>smaller JavaScript bundle and less overhead</li>
<li><strong>interoperability</strong></li>
</ul>

<p>The last point is easy to overlook: Not every project uses React, and if you’re including the stack layout pattern in a Design System or a redistributable UI library, developers could use it in projects using different UI frameworks or a server-side language like PHP or Ruby.</p>

<h2>
  
  
  Nice features and improvements
</h2>

<p>From this base, you can iterate to add more features and improve the developer experience. While some of the following examples target React specifically, they can be easily adapted to other frameworks.</p>

<h3>
  
  
  Control spacing
</h3>

<p>If you're developing a component library you definitely want to define a set of pre-defined spacing variants to make space more consistent. This approach also eliminates the need to explicitly write the style attribute:<br>
</p>

<pre class="brush:php;toolbar:false">.stack {
  --s: 0;
  display: flex;
  flex-direction: column;
  row-gap: calc(var(--s) * 16px);

  &.s\:1 { --s: 1 }
  &.s\:2 { --s: 2 }
  &.s\:4 { --s: 4 }
  &.s\:6 { --s: 6 }
}

/** Usage:
<div>



<p>For a bolder approach to spacing, see Complementary Space by Donnie D'Amato.</p>

<h3>
  
  
  Add better scoping
</h3>

<p>Scoping, in this case, refers to techniques to prevent conflicts with other styles using the same selector. I’d argue that scoping issues affects a pretty small number of projects, but if you are really concerned about it, you could:</p>

<ol>
<li>Use something as simple as CSS Modules, which is well supported in all major bundlers and frontend frameworks.</li>
<li>Use cascade layers resets to prevent external stylesheets from modifying your styles (this is an interesting technique).</li>
<li>Define a specific namespace like .my-app-... for your classes.</li>
</ol>

<p>Here is the result with CSS Modules:<br>
</p>

<pre class="brush:php;toolbar:false">.stack {
  --s: 0;
  display: flex;
  flex-direction: column;
  row-gap: calc(var(--s) * 16px);

  &.s1 { --s: 1 }
  &.s2 { --s: 2 }
  &.s4 { --s: 4 }
  &.s6 { --s: 6 }
}

/** Usage
import * from './styles/stack.module.css'

<div classname="{`${styles.stack}">
    // ...
</div>  
*/

Alternatives

If you still think a polymorphic component would be better, really can't deal with plain HTML, or don’t want to write CSS in a separate file (though I am not sure why), my next suggestion would be to take a look at PandaCSS and create custom patterns or explore other options like vanilla-extract. In my opinion, these tools are an over-engineered CSS metalanguage but still better than a polymorphic component.

Another alternative worth considering is Tailwind CSS, which has the advantage of being interoperable between languages and frameworks.

Using the default spacing scale defined by Tailwind, we could create a stack- plugin like this:

import * as stylex from "@stylexjs/stylex";
import { useState } from "react";

// styles
const styles = stylex.create({
    base: {
        fontSize: 16,
        lineHeight: 1.5,
        color: "#000",
    },
});

export function Toggle() {
    // interactions
    const [toggle, setToggle] = useState(false);
    const onClick = () => setToggle((t) => !t);

    // markup
    return (
        <button type="button" onclick="{onClick}">
            {toggle}
        </button>
    );
}

As a side note: it's interesting that Tailwind uses the component mental model in matchComponents to describe complex CSS rulesets, even if it does not create any real component. Maybe another example of how pervasive the concept is?

Takeaways

The case of Componentitis, beyond its technical aspects, demonstrates the importance of pausing to examine and question our mental models and habits. Like many patterns in software development, components emerged as solutions to real problems, but when we began defaulting to this pattern, it became a silent source of complexity. Componentitis resembles those nutritional deficiencies caused by a restricted diet: the problem isn't with any single food but rather with missing out on everything else.

The above is the detailed content of Not Everything Needs a Component. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
This Isn't Supposed to Happen: Troubleshooting the ImpossibleThis Isn't Supposed to Happen: Troubleshooting the ImpossibleMay 15, 2025 am 10:32 AM

What it looks like to troubleshoot one of those impossible issues that turns out to be something totally else you never thought of.

@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools