DEV Community

Cover image for Styled-Components: The React CSS Hybrid
Miles Ager
Miles Ager

Posted on • Updated on

Styled-Components: The React CSS Hybrid

styled-components and CSS

The styled-components library is the best way to apply style and effects to any application that is using React on the front-end. styled-components give one the ability to create React-like components that extend CSS (Cascading Style Sheets) styles and effects without having to rely on the rigidity of using class, ids, or requiring a styles.css file. I don't want to downplay the importance of CSS, since styled-components extends the CSS language and has almost identical syntax. The more one is accustomed with CSS, the lower their learning curve for styled-components. From my personal experience I almost exclusively use styled-components to apply styles in React front-end apps. The main reason, is because I am a lazy person, and I like finding ways of making things easier to use. I love CSS, and since I first began using CSS, I was drawn to its layers of complexity as well as the opportunity for creativity it provides. However, using selectors like class or id can lead to collisions and specificity issues that are difficult to isolate and debug, particularly as an app increases in size. styled-components provides developers with flexible, reusable, syntactic sugar. For the remainder of my blog post, I will explain, three main aspects of styled-components that help developers like me be less scared when integrating CSS into React components: No longer needing an entire file designated to style, can use props, gives access to createGlobalStyle and ThemeProvider.

Flexibility and Reusability

CSS is such a powerful tool, but in a large app, altering your style with CSS can feel like a game of Jenga. With tradition CSS styling methods, styles are global by default. What feels like a small change to your styles, can end up causing unintentional effects to some other element. That's where the flexibility and modularity of styled-components outperforms CSS. See example below.

import React from 'react';
import styled from 'styled-components';

const Color = styled.h1`
   color: purple;
`; 

const SuperSimpleReactComponent = () => ( 
<>
<Color>Hello World!</ Color>
</>
);


export default SuperSimpleReactComponent;
Enter fullscreen mode Exit fullscreen mode

In the above React component, the work of applying the color style on the element in the implicit return statement was completed in the same file. That is something that the CSS dinosaur just can't do, while styled-components can. But wait, there's more! What if I wanted to make another component also have a purple element being rendered to the DOM, and that component is in another file? You can export styled-components, and import them into the files you want to reuse them in. As seen in the example bellow.

SuperSimpleReactComponent.jsx

import React from 'react';
import styled from 'styled-components';

export const Color = styled.h1`
   color: purple;
`; 

const SuperSimpleReactComponent = () => ( 
<>
<Color>Hello World!</ Color>
</>
);


export default SuperSimpleReactComponent;
Enter fullscreen mode Exit fullscreen mode

SuperSimpleReactComponent2.jsx

import React from 'react';
import Color from './_SuperSimpleReactComponent.jsx_';

const SuperSimpleReactComponent2 = () => ( 
<>
<Color>Hello There!</ Color>
</>
);


export default SuperSimpleReactComponent2;
Enter fullscreen mode Exit fullscreen mode

As seen in the above example we can export the Color component in the SuperSimpleReactComponent.jsx file, and import the Color component to use in the SuperSimpleReactComponent2.jsx file.

Props

styled-components feel as though they are just a natural part of React when one get's used to using the library. I feel this is especially evident in how one can pass props to styled components. Props can be used to add another dimension to how one can control the styles of their project. Example bellow.

import React from 'react';
import styled from 'styled-components';

const Color = styled.h1`
   color: ${props => props.purp ? 'purple' : 'black'};
`; 


const SuperSimpleReactComponent = () => ( 
<>
<Color purp>purple</ Color>
<Color>black</ Color>
<Color purp>purple</ Color>
</>
);


export default SuperSimpleReactComponent;
Enter fullscreen mode Exit fullscreen mode

As seen in the example above, we are able to pass props to our styled-components providing more ways to customize styles in the application. When the purp prop is pass into the Color component, we will the element will be colored purple, while the element without the prop purp.

createGlobalStyle and ThemeProvider

As a dev that still wants to have styles that are applied globally, I like to use the importable helper functions from styled-components, createGlobalStyle and ThemeProvider.
createGlobalStyle is a pretty useful tool when you want a style to be shared across just the elements in one component, shared among a component and its children, or shared across the whole application. No wrapping is needed for createGlobalStyle, just import it wherever you need it, and add it straight into the component's return statement as a self-closing tag.
ThemeProvider works similarly to createGlobalStyle, in that it can be used to provide styles globally. All elements below the ThemeProvider self-closing tag, or wrapped within ThemeProvider can be passed an object containing the styles you want to use. This is particularly useful for helping keep styles consistent and organized across an application. example down below.

import React from 'react';
import { createGlobalStyle, ThemeProvider } from 'styled-components';

const GlobalStyle = createGlobalStyle`
  body {
    font-family: sans-serif;
  }
`;
const theme1 = {
  colors: {
    primary: 'purple',
    secondary: 'black',
  },
};


const CreateThemeGlobalComponent = () => ( 
    <>
        <GlobalStyle />
        <ThemeProvider theme={theme1}>
            <h1>createGlobalStyle and ThemeProvider</h1>
            <h1> are Rad!</h1>
        </ThemeProvider>
            <h1> Use them in your next project!</h1>
    </>
);


export default CreateThemeGlobalComponent;
Enter fullscreen mode Exit fullscreen mode

In the above component I am using createGlobalStyle to apply the font style to the entire component. I have created a theme and I am wrapping elements in ThemeProvider and applying the theme to all elements within.

Final Thoughts

styled-components is a must use for any developer trying to apply style to a React based app. It provides a flexible, user-friendly, modular, approach to using CSS. Although, styled-components help developers more easily apply styles to their app, using styled-components does not make the job of sorting through the complex CSS language for the desired styles any easier.

style-components docs
CSS docs
createGlobalStyle and ThemeProvider

Top comments (0)