Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Last active January 7, 2020 15:58
Show Gist options
  • Save uladzislau-stuk/cd681d9333693ad82cda280633cc00ba to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/cd681d9333693ad82cda280633cc00ba to your computer and use it in GitHub Desktop.
[CSS In JS]

Use cases

Styled components Material UI styled components Material UI css Import styles inside component

Motivation

  • Keeps track of which components are rendered on a page and injects their styles and nothing else
  • Generate unique class names for components
  • Dynamic styling (props)
  • Automatic vendor prefixing

Note: Higly recommended to use Babel Plugin. See official doc for more details

Get started

// Create a Title component that'll render an <h1> tag with some styles
const Title = styled.h1`
  font-size: ${props => props.big || "1em"};
  text-align: center;
  color: palevioletred;
`;

// Extending
const CustomTitle = styled(Title)`
	//...
`

In some cases you might want to change which tag or component a styled component renders. This is common when building a navigation bar for example, where there are a mix of anchor links and buttons but they should be styled identically.

You can use polymorhic "as" props

Pseudoelements, pseudoselectors, and nesting

They use prepr-r stylish

const Thing = styled.div.attrs((/* props */) => ({ tabIndex: 0 }))`
  &:hover {
    color: red; // <Thing> when hovered
  }

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

Attaching 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",
}))`
  color: palevioletred;
  font-size: 1em;
  border: 2px solid palevioletred;
  border-radius: 3px;

  /* here we use the dynamically computed prop */
  margin: ${props => props.size};
  padding: ${props => props.size};
`;

Animations

CSS animations with @keyframes aren't scoped to a single component.

Note: export a keyframes helper which will generate a unique instance that you can use throughout your app: Note: keyframe is not supported by React Native. Use ReactNative.AnimatedAPI

All shared style fragment should use css helper!

const rotate = keyframes``

// ❌ This will throw an error!
const styles = `
  animation: ${rotate} 2s linear infinite;
`;

// ✅ This will work as intended
const styles = css`
  animation: ${rotate} 2s linear infinite;
`

React Native

For RN use css-to-react-native

Usage with metro bundler

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