Reputation: 5613
I am using styled-components along with Gatsby. I used styled-components to style the Link
component provided by Gatsby for my home page.
const HomePageLink = styled(Link)`
display: inline-block;
font-size: ${fontSizes.xxlarge};
text-decoration: none;
box-shadow: none;
:link,
:visited {
color: ${colors.slate};
}
:hover,
:active {
color: ${colors.red};
}
`
However I realize that I also need to style a plain html <a />
tag using the exactly same style. I wonder is there a way to make the style component above adapt to <a />
tags without duplicating the code like this
const HomePageAnchorTag = styled.a`
display: inline-block;
font-size: ${fontSizes.xxlarge};
text-decoration: none;
box-shadow: none;
:link,
:visited {
color: ${colors.slate};
}
:hover,
:active {
color: ${colors.red};
}
`
Upvotes: 1
Views: 1827
Reputation: 53874
Yes, use css
API which allows you to construct reusable CSS blocks.
A helper function to generate CSS from a template literal with interpolations.
import styled, { css } from 'styled-components';
const reusableCSS = css`
display: inline-block;
font-size: ${fontSizes.xxlarge};
text-decoration: none;
box-shadow: none;
:link,
:visited {
color: ${colors.slate};
}
:hover,
:active {
color: ${colors.red};
}
`;
const HomePageAnchorTag = styled.a`
${reusableCSS}
`;
const HomePageLink = styled(Link)`
${reusableCSS}
`;
Usually, you will notice a mixins.js
file that contains exports of reusable css
block, for example:
// mixins.js
const flexCenter = css`...`
export default { flexCenter };
// usage inside styled components.
${mixins.flexCenter}
Upvotes: 6