Skip to content

Instantly share code, notes, and snippets.

@carl0zen
Last active December 8, 2021 05:51
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save carl0zen/7704cce24edba0520eb6b36d894f04ae to your computer and use it in GitHub Desktop.
Save carl0zen/7704cce24edba0520eb6b36d894f04ae to your computer and use it in GitHub Desktop.
Styled Components Mixin example
// Mixin like functionality
const textInput = props => `
color: ${props.error ? color.white : color.base};
background-color: ${props.error ? color.alert : color.white};
`;
export const Input = styled.input`
${textInput}
`;
export const Textarea = styled.textarea`
${textInput};
height: ${props => props.height ? props.height : '130px'}
resize: none;
overflow: auto;
`;
@avxkim
Copy link

avxkim commented Feb 18, 2020

You also can do that:

const linkSharedStyles = css`
  color: white;
`;

const Logo = styled(Navbar.Link)`
  ${linkSharedStyles};
`;

@IngridSurya
Copy link

You also can do that:

const linkSharedStyles = css`
  color: white;
`;

const Logo = styled(Navbar.Link)`
  ${linkSharedStyles};
`;

error 'css' is not defined ...

@avxkim
Copy link

avxkim commented Feb 23, 2020

@IngridSurya

import styled, { css } from 'styled-components';

@IngridSurya
Copy link

@IngridSurya

import styled, { css } from 'styled-components';

ah right, thanks !

@starikcetin
Copy link

You also can do that:

const linkSharedStyles = css`
  color: white;
`;

const Logo = styled(Navbar.Link)`
  ${linkSharedStyles};
`;

Adding on:
vscode-styled-components highlights the css blocks as well.

@jens1101
Copy link

Just to add my 2 cents, you can re-use mixins for different pseudo classes or elements.

Here is an example mixin:

import { css } from 'styled-components';

export const shadowMixin =({ boxShadow }) => css`
  ${boxShadow && `box-shadow: ${boxShadow};`}
`;

And you can use it like such:

import styled from 'styled-components/macro';

export const Button = styled.button`
  ${props => shadowMixin({ boxShadow: props.boxShadow })}

  :hover {
    ${props => shadowMixin({ boxShadow: props.hoverBoxShadow })}
  }
`;

Note that I was able to reuse the mixin for the hover state.

That button component could then be used like this:

<Button
  boxShadow={'0 0 3px black'}
  hoverBoxShadow={'0 0 5px red'}
>
  My button with shadow
</Button>

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