Skip to content

Instantly share code, notes, and snippets.

@rheaditi
Last active September 10, 2019 08:16
Show Gist options
  • Save rheaditi/2bd081fe18536a33a3a2860bca32e6cb to your computer and use it in GitHub Desktop.
Save rheaditi/2bd081fe18536a33a3a2860bca32e6cb to your computer and use it in GitHub Desktop.
styled-components: Add styles to existing component

styled-components: Apply your custom styles to a third party/existing component

topics: styled-components, Link, react-router, react-router-dom, custom styles, extend component, styling third party components

Usage

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!

Demo

See a demo of it on code-sandbox.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment