Projects Blog

How to add target attribute to social icons in Starlight

Starlight is the new documentation framework for Astro. It offers a lot of build-in components and configurations.

Recently, I found myself in a situation where I needed to make a slight modification to one of its components: the SocialIcons.

Of course, Astro team had thought of this, so they added a method to override components.

In my case, I wanted to add the target="_blank" and rel="noopener noreferrer" into the social icons.

To achieve this, simply navigate to node_modules/@astrojs/starlight/components, locate the component code, and make the necessary tweaks.

SocialIcons.astro
---
import type { Props } from '@astrojs/starlight/props'
import { Icon } from '@astrojs/starlight/components'
import config from 'virtual:starlight/user-config'
type Platform = keyof NonNullable<typeof config.social>
type SocialConfig = NonNullable<NonNullable<typeof config.social>[Platform]>
const links = Object.entries(config.social || {}) as [Platform, SocialConfig][]
---
{
links.length > 0 && (
<>
{links.map(([platform, { label, url }]) => (
<a
href={url}
target='_blank'
rel='noopener noreferrer'
class='sl-flex'
>
<span class='sr-only'>{label}</span>
<Icon
size='1.5em'
name={platform}
/>
</a>
))}
</>
)
}
<style>
a {
color: var(--sl-color-text-accent);
padding: 0.5em;
margin: -0.5em;
}
a:hover {
opacity: 0.66;
}
</style>

Then, add this component in the components configuration of the starlight Astro integration.

astro.config.js
import { defineConfig } from 'astro/config'
import starlight from '@astrojs/starlight'
export default defineConfig({
integrations: [
starlight({
components: {
SocialIcons: './src/components/starlight/SocialIcons.astro',
},
}),
],
})

If you need, override and customize any component from this list to suit your specific requirements.


In conclusion, these steps offer a very simple method to customize our Starlight documentation site to suit our specific requirements.

Starlight emerges as a versatile and user-friendly documentation framework, providing developers with a wide range of components and customization possibilities. This allows for easy adjustments to meet the unique needs of our project without unnecessary complexity.

Happy coding! 🚀

Related posts