topics: styled-components, Link, react-router, react-router-dom, custom styles, extend component, styling third party components
Let's take the example of react-router-dom's Link component which you may want to style as your own HyperLink component.
Say you have created a styled.a component called HyperLink.
const HyperLink = styled.a`
color: rgb(219, 112, 147);
cursor: pointer;
text-decoration: underline;
`;Now, you'd like to add the styles, say, from a component library & style the React Router link component the same way.
Using styled-components' concepts of extending styles, "as" polymorphic prop and attaching additional props together, we can achieve it the following way:
// 'path/to/components/Link'
import { Link as ReactRouterLink } from 'react-router-dom';
import HyperLink from './styles';
const Link = styled(HyperLink).attrs({ as: ReactRouterLink })``;
export default Link;And that's it!