Higher-Order Components

Learn how we can build higher-order components (HOCs) in Astro.

Higher-order components (HOCs) are a pattern used for reusing component logic. Just like higher-order functions in JavaScript, Astro can leverage the same compositional nature but with components. Let’s take a look at a simple example that we can use in Astro.

HOCs in Astro

A common use case for an HOC is to conditionally wrap elements—for example, we might want to wrap images with a link if a link is provided for the image. Traditionally, this is done through the use of a ternary operator, like so:

Press + to interact
---
const {
image,
link
} Astro.props
---
{link ? (
<a href={link}>
<img {...image} />
</a>
) : (
<img {...image} />
)}

This is a simple example but it can get more complicated with nested elements. This pattern often emerges for larger codebases where a lot of conditions are present. This can worsen code readability and maintainability, which, in turn, increases time spent on development. We can get around this using an HOC. Let’s see how we can create an HOC in Astro for this type of behavior.

Press + to interact
---
const { condition } = Astro.props;
const wrapper = await Astro.slots.render('wrapper');
const children = await Astro.slots.render('default');
const wrapped = wrapper?.replace('children', children);
if (!Astro.slots.has('wrapper')) {
console.error('Missing wrapper. Add slot="wrapper" to one of the elements.');
}
---
<Fragment set:html={condition ? wrapped : children} />

This HOC works as a wrapper. We can use it to conditionally wrap elements with other elements if necessary. It works by using named slots in Astro. It works in the following way:

  • Line 2: The condition prop is accepted, which ultimately decides whether to wrap the element or not. ...