Styled components cheat sheet for React
Tags: styledcomponents, webdev, react, javascript
Published: 2021-06-16 16:17:59

The use of Styled components in React.js app development has become quiet popular in the last few years, its popularity is mainly due to the fact that it provides a better developer experience when it comes to writing styles for your app. Traditionally you would have one long css style sheet with all your styling centralized in one place. The  problems that you commonly face are CSS name clashes and styling problems due to specificity issues. As well as styled components, many other solutions address these problems particularly BEM, sass, CSS modules, and they all have their pros and cons. This article is not going to discuss which is best to use but rather provide a cheat sheet for styled components. There's also a video that I made on this as well.
{% youtube A35oMQCAtBI %}

Four things that makes me want to use styled components in the future are:

1] Scope level styles, ie component and styles are grouped together, so you dont have to do much searching around finding the style that is breaking your UI.
2] Use of variables and ability to inject props into your components. Yes its dynamic and can use programming logic!
3] No need to waste time thinking up unique class names.
4] Easy to learn.

##Lets look at how to code your first styled component

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sb5lpagl2wa273f2snvp.jpg)

As you can see from the three steps shown above, its quiet easy. You might find the declaration a bit odd because we are calling the styled component function with back ticks.

```const Button = styled.button`color:red;` ``` 
 but this is really same as making a normal function call and passing an array:
```const Button = styled.button([`color:red;`]) ```

Calling function without the brackets and putting your arguments between back ticks is called tagged template literals, this is a Javascript feature. When tagged template literals are interpreted, there will always be one argument that will be of type array.

To see some examples and [read more about tagged template literals, go to Wes Bos article](https://wesbos.com/tagged-template-literals)

From Wes Bos's article you learn that you can inject variables into tagged template literals. So in styled components you can do the following:

```jsx 
let primary_color='red';
const Button = styled.button`color:${primary_color};` 
```

This is what gives styled components super powers and you can do all sorts of tricks with it.


## Here is a cheat sheet for beginners who are using styled components for the first time
Here are some code snippets that will help you get started and make the most of styled components. The code examples in this cheat sheet assumes you have created a basic app using npx create-react-app.

#### 1] install
```
npm install styled-components
yarn add styled-components
```
#### 2] Import into your scripts
```jsx 
// then, just import it into your script like:
import styled from "styled-components"
```

#### 3] Basic styling of elements ie h1,h2,div,input,span etc
```jsx 
//Declare wrapper for a h2 element with styling like this
const Headline = styled.h2`
  color: black;
  border-bottom:1px solid black;
`
function App() {
  //Use Headline wrapper component in your app 
  return (
    <Headline>
      The Headline goes here
    </Headline>
  )
}
```
There are methods for all html elements so you can style a `<diV>` by using ` styled.div` , or style `<input>` by using ` styled.input` 

#### 4] Include Pseudo-classes like :hover, :focus, :active etc, by pre-fixing a '&'. Like `&:hover {.....}` 

```jsx
    const Button = styled.button`
        width:100px;
        color:white;
        background-color: green;
        
        //Add hover styling
        &:hover {
            background-color:gray;
        }

    };`
```

#### 5] Include media queries in your styled components.

```jsx
    const Wrapper = styled.div`
    width:50vw;
    
    //Make it full width on smaller screens 
    @media screen and (max-width: 800px) {
        background-color: lightgray;
        width:100vw;

    }
    `
```

#### 6] Extending styles in your styled component - You can use a base style, then extend that with new style rules

```jsx
// Base style for heading 
const Headline = styled.h1`
  border-bottom:2px solid gray;
  color: blue;
`;

//Extend base style to overide color
const HeadlineGreen = styled(Headline)`
  color: green;
`;

function App() {
  return (
    <>
      
      <Headline>
        Standard Blue headline
      </Headline>
      <HeadlineGreen>
        Extended green headline 
      </HeadlineGreen>
    </>
  );
}


```
If you look carefully at HeadlineGreen declaration you would see that we are passing Headline as an argument ie ```jsx
const HeadlineGreen = styled(Headline)`.....`
```


#### 7] You can still use classes and write styles for selectors like normal css styling

```jsx

//Style everything inside the wrapper with css selectors
const Wrapper = styled.div`
  width:100%;
  
  .big-heading {
      border-bottom:2px solid blue;
      color: blue;
  }
  button.primary {
    width:100px;
    height:50px;
    background-color:green;
    color:white;
  }
`

function App() {
  return (
    <Wrapper>      
      <h2 className='big-heading'>
        Standard Blue headline
      </h2>
      <button className='primary'>
        A plain Button
      </button>
    </Wrapper>
  );
}
export default App;

```


#### 8] You can pass props to your styled component
```jsx
const Headline = styled.h1`
  color: ${props => props.color};
`
function App() {
  return (
    <>
      {/* We are passing color as a prop, we also set its value to pink*/}
      <Headline color="pink">
        Standard Blue headline
      </Headline>
    </>
  );
}
export default App;
```
In the above code we are setting the color of Headline dynamically, depending on what is passed as props for the color attribute. You can access props by writing a fragment of code like: `${props => props.color}` and in the JSX we set it like `<Headline color="pink">.....</Headline>`

#### 9] How to apply global styles that target `<body>` and `<html>` or  where to put your reset styles.

```jsx
import styled,{createGlobalStyle} from 'styled-components';
// Remember to import createGlobalStyle as above

const GlobalStyle = createGlobalStyle`
    * {
        margin: 0;
        padding: 0;
    }

    body {
        background: teal;
        font-family: Open-Sans, Helvetica, Sans-Serif;
    }
`;

function App() {
  return (
    <> {/*Place the GlobalStyle tag at the very top of your app component tree.*/}
      <GlobalStyle />
      <h1>
        This is a landing page
      </h1>
    </>
  );
}
```
Remember to import createGlobalStyle from styled-components like this:`import styled,{createGlobalStyle} from 'styled-components';`. You can place the tag <GlobalStyle /> at the very top of your app component tree. 

## Hope you enjoy using styled components
So I hope this introduction cheat sheet to styled components gets you off and running in your next project. Remember this is just the tip of the ice-burg. You can do so much with it.