DEV Community

Cover image for Styled components cheat sheet for React
Keerthi
Keerthi

Posted on • Updated on

Styled components cheat sheet for React

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.

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

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

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:

let primary_color='red';
const Button = styled.button`color:${primary_color};` 
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

2] Import into your scripts

// then, just import it into your script like:
import styled from "styled-components"
Enter fullscreen mode Exit fullscreen mode

3] Basic styling of elements ie h1,h2,div,input,span etc

//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>
  )
}
Enter fullscreen mode Exit fullscreen mode

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 {.....}

    const Button = styled.button`
        width:100px;
        color:white;
        background-color: green;

        //Add hover styling
        &:hover {
            background-color:gray;
        }

    };`
Enter fullscreen mode Exit fullscreen mode

5] Include media queries in your styled components.

    const Wrapper = styled.div`
    width:50vw;

    //Make it full width on smaller screens 
    @media screen and (max-width: 800px) {
        background-color: lightgray;
        width:100vw;

    }
    `
Enter fullscreen mode Exit fullscreen mode

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

// 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>
    </>
  );
}


Enter fullscreen mode Exit fullscreen mode

If you look carefully at HeadlineGreen declaration you would see that we are passing Headline as an argument ie

const HeadlineGreen = styled(Headline)`.....`
Enter fullscreen mode Exit fullscreen mode

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


//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;

Enter fullscreen mode Exit fullscreen mode

8] You can pass props to your styled component

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;
Enter fullscreen mode Exit fullscreen mode

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.

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>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Remember to import createGlobalStyle from styled-components like this:import styled,{createGlobalStyle} from 'styled-components';. You can place the tag 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.

Oldest comments (3)

Collapse
 
0xahmad profile image
Ahmad

I will definitely give it a shot with my next project. But how good is it in DRY; compared to sass with reusable modules/components?

Collapse
 
keefdrive profile image
Keerthi

In my opinion, they (sass, css modules, and styled-components) are all good if you implement them correctly and sensibly so that you are not re-inventing the wheel. Using sass , there is that little overhead of learning how to write mixins/functions etc, whereas in styled-components you apply the same JS programming logic, this results in less of a learning curve for react developers.

Collapse
 
0xahmad profile image
Ahmad

Hmm thanks for the feedback will keep thst in my mind. Thanks 👋