Styled Components Cheat Sheet

In the age of NPM, nobody needs .CSS files

#Basics

Installing & Initializing

yarn add styled-components
// or:
npm install styled-components
// then, just import it:
import styled from "styled-components"
Styled Components is a library that can be installed normally via NPM. It uses JavaScript to generate CSS code at runtime to style components in React.js.

First styled-component

const Headline = styled.h1`
  color: green;
`
function App() {
  return (
    <Headline>
      The Headline
    </Headline>
  )
}
With styled components we create a React.js component by calling the styled function. We pass the actual CSS code to it and also specify what kind of HTML it is.
Headline is nothing else than a h1-tag with CSS styles.

More Styles

const Headline = styled.h1`
    color: green;
    font-size: 25px;
    margin: 0;
`
We can of course add multiple CSS attributes. Styled Components uses the exact same syntax as CSS.

Extending Styles

const Headline = styled.h1`
  color: green;
`
const HeadlineItalic = styled(Headline)`
  font-style: italic;
`
HeadlineItalic is now Green AND Italic.

#Using Component Props

Using a prop for the color

const Headline = styled.h1`
  color: ${props => props.color};
`

function App() {
  return (
    <Headline color="red">
      Text 
    </Headline>
  )
}
Now, the headline is red, since we pass this as color.

Conditionals as props

const Headline = styled.h1`
  visibility: ${props => (
    props.show ? "visible" : "hidden")
  };`

function App() {
  return (
    <Headline show={false}>
      Text 
    </Headline>
  )
}
The component will be hidden, since we pass false, this sets hidden as value.

Theme Props

import styled, { ThemeProvider} from "styled-components"

const Head = styled.h1`
  color: ${props => props.theme.main};
`
const theme = {
  main: "#14114a"
}

function App() {
  return (
    <ThemeProvider theme={theme}>
      <Head>Headline</Head>
    </ThemeProvider>
  )
}

#Advanced

Styling existing Components

const Headline = ({ className, children}) => (
  <h1 className={className}>{children}</h1>
)
  
const HeadlineStyled = styled(Headline)`
  color: red;
`
Every component that uses className as props for styling can also be styled afterwards with styled components. Also third-party-components.

Using Style Objects

const Headline = styled.h1({
  color: "red",
  fontSize: "50px"
})
Yes, it is the same syntax as in React Native - if you want to, you can use this syntax instead of backticks.

Connecting Components

const Wrapper = styled.div`
  height: 400px;
  width: 400px;
  background-color: green;
`
const Text = styled.div`
  color: red;
  ${Wrapper}:hover & {
    color: blue;
}`
<Wrapper>
  <Text>Some Text</Text>
</Wrapper>
When now hovering over the Wrapper-Div, the text inside of it, changes it color.