Skip to content

Instantly share code, notes, and snippets.

@carl0zen
Last active December 8, 2021 05:51
Show Gist options
  • 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;
`;
@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