Thu Jun 02 2022

Map through props and apply CSS inside Styled Components

How to map through the props passed into a styled component and apply styling


During the process of upgrading my website, I came across an interesting problem where I needed to pass an array of strings to a styled component I created.

I was passing this array of strings as I wanted to add a special colour and text-decoration style to <a> tags with those href links.

1<IntroContent minHeight="65vh" href={["blog", "search"]}>
2 <p>Click on the below to scroll</p>
3 { => {
4 if (tag !== "homepage-content")
5 return (
6 <Tag key={tag}>
7 <Link href={`#${tag}`}>{tag}</Link>
8 </Tag>
9 );
10 })}
11 Alternatively, you can also visit the <Link href="/blog">blog</Link> 📖 or{" "}
12 {""}
13 <Link href="/search">search</Link> 🔍 to search


Here is how I accessed the array that was being passed as a prop and mapped over it to apply styles

1export const IntroContent = styled.div<{
2 minHeight?: string;
3 href?: string[];
5 //some other code here
6 ${({ href }) =>
7 href?.map(
8 (link) => css`
9 a[href*=${link}] {
10 color: blue;
11 text-decoration: underline;
12 }
13 `
14 )}

If you are curious about how I am able to target <a> tags with these specific href values, it's thanks to CSS attribute selectors which match elements based on the presence or value of a given attribute.

The css we have wrapped the attribute selector with is a helper function to generate CSS from a template literal with interpolations. You can read more about it here.

Did this article help you or do you have another better way of achieving the same? Let me know in the comments below!