Home Web Front-end CSS Tutorial Making headless components easy to style

Making headless components easy to style

Aug 23, 2024 pm 02:30 PM

Making headless components easy to style

Is a headless component simply an unstyled component, or is there more to it?

The web already separates style from content by requiring styles to be defined
in CSS instead of HTML. This architecture allows each web page to adopt a global
design standard without defining any page-specific styles.

As the web evolved into an application platform, developers sought ways to make
their growing codebases more maintainable. Nowadays, the defacto strategy for
organising application code is to define small, lightweight components that can
be composed together. Thus, the component became the unit of composition in
modern web development.

Components often define both their HTML and CSS in the interest of encapsulation.
While this makes them easier to compose, they can be more difficult to
incorporate into an existing design system cohesively. This is especially true
for third-party components that are imported from external vendors.

Headless components solves this challenge by reintroducing a separation between
content and style. However now the separation is along the component boundary as
opposed to between HTML and CSS. They key to creating a great headless component
lies in designing the component's interface such that a developer can
clearly and easily apply their own styles.

Forward relevant props

In the most basic sense, a headless component is simply an unstyled component.
Developers must be able to apply their own CSS to the HTML elements that the
component defines.

For simple components, this may simply be a matter of forwarding the className
prop to the root element so that developers can use class selectors in their
CSS.

If your component has the same semantics as a native HTML element, you can use
the ComponentProps type from React to ensure that all relevant props are
forwardable. Remember to omit any props that you don't want the user of
your component to be able to override.

import { type ComponentProps } from 'react'

function SubmitButton({ ...props }: Omit<ComponentProps<'button'>, 'type'>) {
  return <button type="submit" {...props} />
}
Copy after login

Provide predefined classes

For components that contain one or more child elements, developers will probably
want to style each element individually.

One strategy to support this is to rely on
CSS combinators.
For example, a headless gallery component might be styled like this:

/* Root container */
.gallery {
}

/* Gallery items container */
.gallery > ul {
}

/* Gallery item */
.gallery > ul > li {
}

/* Next and Previous buttons */
.gallery button {
}
Copy after login

But this approach creates a huge problem because now the internal HTML structure of
the component is part of its public API. This prevents you from modifying the
structure later without potentially breaking downstream code.

A better strategy is to predefine classes for each major child element. This way
developers can use class selectors without depending on any particular HTML
structure:

.xyz-gallery {
}

.xyz-gallery-next-button {
}

.xyz-gallery-previous-button {
}

.xyz-gallery-items-container {
}

.xyz-gallery-item {
}
Copy after login

Remember to prefix your classes so that they don't clash with the
developer's own styles.

Support custom layouts

Providing predefined classes is perhaps the quickest way to enable developers to
style your component. However, a disadvantage with this approach is that the
HTML structure cannot be customised.

This may not matter. After all, plain HTML is already pretty flexible in how it
can be rendered. However sometimes developers reach for additional HTML in order
to accomplish certain designs. If you view the source code for almost any
website, you can expect to see a multitude of unsemantic

elements,
whose sole purpose is to define flex or grid layouts, visually group child
elements within a border or create new stacking contexts.

You can support such uses cases by splitting your headless component up into
multiple related components. This way developers are free to add their own
layout elements to the component. For example, a developer could embed the Next and
Previous buttons from the gallery example within a custom flexbox container:

<Gallery>
  <GalleryItems className='gallery-items-container'>
    {data.map((item) => (
      <GalleryItem key={item.id}>{item.content}</GalleryItem>
    ))}
  </GalleryItems>
  <div className='gallery-buttons-container'>
    <GalleryPreviousButton>
    <GalleryNextButton>
  </div>
</Gallery>
Copy after login
.gallery-items-container {
}

.gallery-buttons-container {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
}
Copy after login

These kinds of components are typically implemented using
context to pass
data between themselves. They require more work to design, implement and
document. However, their resulting versatility often means the extra effort is
worth it.

Allow components to be overridden

A small number of use cases require that a headless component manages the layout
of its child components. An example might be a heirarchical tree view that
allows its items to be reordered via drag and drop. Another use case might be to
allow single-page applications to replace the default anchor element with a
custom link component that facilitates client-side routing.

An advanced strategy for allowing developers to define custom layouts is to
allow the actual child component being rendered to be overriden via props:

<TreeView
  nodes={[...]}
  components={{
    CustomRow,
    CustomDragPreview: (props) => <div className="drag-preview" {...props} />
  }}
/>
Copy after login

This grants the developer full control over what is rendered in each child
component, while allowing the headless component to manage its overall
structure.

You can even allow developers to customise the root element of your component
via a prop. For example, this button component allows a developer to render it
as something else:

import { type ElementType } from 'react'

function HeadlessButton({ as, ...props }: { as?: ElementType }) {
  const Component = as ?? 'button'
  return <Component {...props} />
}
Copy after login

For example, in order for assistive technology to treat the button like a link,
the developer can specify that an anchor element should be used to render the
button:

<HeadlessButton as="a">Actually a link</HeadlessButton>
Copy after login

Summary

Headless components are much more than components that don't contain any
styles. Great headless components are fully extensible and allow the developer
to customise the entire internal HTML structure.

The above is the detailed content of Making headless components easy to style. 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 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
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

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

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

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

See all articles