styled components - rkaku/udemy-typescript-react GitHub Wiki

Props

const Button = styled.button`
  background: ${props => props.primary ? "palevioletred" : "white"};
  color: ${props => props.primary ? "white" : "palevioletred"};

Extend

const TomatoButton = styled(Button)`
  color: tomato;
  border-color: tomato;
`;

As

<Button as="a" href="/">Link with Button styles</Button>

Children

const ReversedButton = props => (
  <Button {...props} children={props.children.split('').reverse()} />
)

render(
  <div>
    <Button as={ReversedButton}>
      Custom Button
    <Button>
  </div>
);

Class Name

const Link = ({ className, children }) => (
  <a className={className}>
    {children}
  </a>
);

const StyledLink = styled(Link)`
`;

render(
  <div>
    <StyledLink>Styled, exciting Link</StyledLink>
  </div>
);

Props

const Input = styled.input`
  color: ${props => props.inputColor || "palevioletred"};
`;


render(
  <div>
    <Input
      defaultValue="@geelen"
      type="text"
      inputColor="rebeccapurple"
    />
  </div>
)

Outside

const StyledWrapper = styled.div`
  /* ... */
`

const Wrapper = ({ message }) => {
  return <StyledWrapper>{message}</StyledWrapper>
}

Hover

const Thing = styled.button`
  color: blue;

  ::before {
    content: '🚀';
  }

  :hover {
    color: red;
  }
`

render(
  <Thing>Hello world!</Thing>
)

Ampersand

const Thing = styled.div.attrs((/* props */) => ({ tabIndex: 0 }))`
  color: blue;

  &:hover {
    color: red; // <Thing> when hovered
  }

  & ~ & {
    background: tomato;
    // <Thing> as a sibling of <Thing>, but maybe not directly next to it
  }

  & + & {
    background: lime; // <Thing> next to <Thing>
  }

  &.something {
    background: orange;
    // <Thing> tagged with an additional CSS class ".something"
  }

  .something-else & {
    border: 1px solid;
    // <Thing> inside another element labeled ".something-else"
  }
`

No &

const Thing = styled.div`
  color: blue;

  .something {
    border: 1px solid;
    display: block;
    // an element labeled ".something" inside <Thing>
  }
`

&&

const Thing = styled.div`
  && {
    color: blue;
  }
`

Additional Props

const Input = styled.input.attrs(props => ({
  // we can define static props
  type: "password",

  // or we can define dynamic ones
  size: props.size || "1em",
}))`
  /* here we use the dynamically computed prop */
  margin: ${props => props.size};
  padding: ${props => props.size};
`;

Animation

const rotate = keyframes`
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
`;

const Rotate = styled.div`
  display: inline-block;
  animation: ${rotate} 2s linear infinite;
  padding: 2rem 1rem;
  font-size: 1.2rem;
`;

render(
  <Rotate>&lt; 💅 &gt;</Rotate>
);
const styles = css`
  animation: ${rotate} 2s linear infinite;
`
⚠️ **GitHub.com Fallback** ⚠️