Home Web Front-end CSS Tutorial Not 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 {...stylex.props(styles.base)} type="button" onClick={onClick}>
            {toggle}
        </button>
    );
}
Copy after login
Copy after login
Copy after login

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' {onclick}>
    {toggle}
</button>

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

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 />} />
            <Body>
                <Stack spacing={2}>
                    <Item>Item 1</Item>
                    <Item>Item 2</Item>
                    <Item>Item 3</Item>
                </Stack>
            </Body>
            <Footer />
        </Layout>
    );
}
Copy after login
Copy after login

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<{ spacing?: number }>) {
    return (
        <div {...stylex.props(styles.root, styles.spacing(spacing))}>
            {children}
        </div>
    );
}
Copy after login
Copy after login

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 {...stylex.props(styles.base)} type="button" onClick={onClick}>
            {toggle}
        </button>
    );
}
Copy after login
Copy after login
Copy after login

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' {onclick}>
    {toggle}
</button>

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

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 />} />
            <Body>
                <Stack spacing={2}>
                    <Item>Item 1</Item>
                    <Item>Item 2</Item>
                    <Item>Item 3</Item>
                </Stack>
            </Body>
            <Footer />
        </Layout>
    );
}
Copy after login
Copy after login

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<{ spacing?: number }>) {
    return (
        <div {...stylex.props(styles.root, styles.spacing(spacing))}>
            {children}
        </div>
    );
}
Copy after login
Copy after login

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
            {...props}
            {...stylex.props(styles.root, styles.spacing(spacing))}
        >
            {children}
        </Component>
    );
}
Copy after login

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);
}
Copy after login
export function Page() {
    return (
        <Layout>
            <Header nav={<Nav />} />
            <Body>
                <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} ${styles.s2}`}>
    // ...
</div>  
*/
Copy after login

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 {...stylex.props(styles.base)} type="button" onClick={onClick}>
            {toggle}
        </button>
    );
}
Copy after login
Copy after login
Copy after login

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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Weekly Platform News: HTML Loading Attribute, the Main ARIA Specifications, and Moving from iFrame to Shadow DOM Apr 17, 2025 am 10:55 AM

In this week&#039;s roundup of platform news, Chrome introduces a new attribute for loading, accessibility specifications for web developers, and the BBC moves

Some Hands-On with the HTML Dialog Element Some Hands-On with the HTML Dialog Element Apr 16, 2025 am 11:33 AM

This is me looking at the HTML element for the first time. I&#039;ve been aware of it for a while, but haven&#039;t taken it for a spin yet. It has some pretty cool and

Paperform Paperform Apr 16, 2025 am 11:24 AM

Buy or build is a classic debate in technology. Building things yourself might feel less expensive because there is no line item on your credit card bill, but

Weekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading Indicator Weekly Platform News: Text Spacing Bookmarklet, Top-Level Await, New AMP Loading Indicator Apr 17, 2025 am 11:26 AM

In this week&#039;s roundup, a handy bookmarklet for inspecting typography, using await to tinker with how JavaScript modules import one another, plus Facebook&#039;s

Where should 'Subscribe to Podcast' link to? Where should 'Subscribe to Podcast' link to? Apr 16, 2025 pm 12:04 PM

For a while, iTunes was the big dog in podcasting, so if you linked "Subscribe to Podcast" to like:

Options for Hosting Your Own Non-JavaScript-Based Analytics Options for Hosting Your Own Non-JavaScript-Based Analytics Apr 15, 2025 am 11:09 AM

There are loads of analytics platforms to help you track visitor and usage data on your sites. Perhaps most notably Google Analytics, which is widely used

See all articles