search
HomeWeb Front-endCSS TutorialMaking headless components easy to style

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>, 'type'>) {
  return <button type="submit"></button>
}
</componentprops>

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 {
}

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 {
}

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>
  </gallerynextbutton></gallerypreviousbutton>
</div>
</gallery>
.gallery-items-container {
}

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

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:> <div classname="drag-preview"></div>
  }}
/>
</treeview>

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></component>
}

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>

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
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
Demystifying Screen Readers: Accessible Forms & Best PracticesDemystifying Screen Readers: Accessible Forms & Best PracticesMar 08, 2025 am 09:45 AM

This is the 3rd post in a small series we did on form accessibility. If you missed the second post, check out "Managing User Focus with :focus-visible". In

Adding Box Shadows to WordPress Blocks and ElementsAdding Box Shadows to WordPress Blocks and ElementsMar 09, 2025 pm 12:53 PM

The CSS box-shadow and outline properties gained theme.json support in WordPress 6.1. Let's look at a few examples of how it works in real themes, and what options we have to apply these styles to WordPress blocks and elements.

Working With GraphQL CachingWorking With GraphQL CachingMar 19, 2025 am 09:36 AM

If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

Making Your First Custom Svelte TransitionMaking Your First Custom Svelte TransitionMar 15, 2025 am 11:08 AM

The Svelte transition API provides a way to animate components when they enter or leave the document, including custom Svelte transitions.

Classy and Cool Custom CSS Scrollbars: A ShowcaseClassy and Cool Custom CSS Scrollbars: A ShowcaseMar 10, 2025 am 11:37 AM

In this article we will be diving into the world of scrollbars. I know, it doesn’t sound too glamorous, but trust me, a well-designed page goes hand-in-hand

Show, Don't TellShow, Don't TellMar 16, 2025 am 11:49 AM

How much time do you spend designing the content presentation for your websites? When you write a new blog post or create a new page, are you thinking about

Building an Ethereum app using Redwood.js and FaunaBuilding an Ethereum app using Redwood.js and FaunaMar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

What the Heck Are npm Commands?What the Heck Are npm Commands?Mar 15, 2025 am 11:36 AM

npm commands run various tasks for you, either as a one-off or a continuously running process for things like starting a server or compiling code.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools