DEV Community

Cover image for A simple global styling method with styled component.
Marizoo
Marizoo

Posted on

4 1

A simple global styling method with styled component.

Using Styled-components, I have tried several ways to apply global styling & media queries to my React App. I'm here to share my preferred method this far (until I find another better way, of course!).

(For this article, I am using React version 17.0.2, and styled component version 5.3.3) Here it is, in step by step format:

Step 01.

  • Install styled components
yarn add styled-components

//or

npm install styled-components

Enter fullscreen mode Exit fullscreen mode

Step 02.

  • Inside the src folder: create a file, and call it globalStyle.js
  • Here is a screenshot of my folder structure

screenshot of my folder structure

  • Inside globalStyle.js, add these codes:
import { css } from "styled-components";

// Create global color
export const ctaColor = () => {
  return css`
        palevioletred
    `;
};

// Create media queries
export const mobile = (props) => {
  return css`
    @media (min-width: 576px) {
      ${props}
    }
  `;
};

Enter fullscreen mode Exit fullscreen mode

- as you can see, we are simply creating functions that return CSS for us

Step 03.

  • To use these "CSS-functions" in our components: just import it, then apply it to our styling.

  • It works just like the usual JavaScript functions.

  • Refer to the codes below for some examples:

import styled from "styled-components";
import { mobile, ctaColor } from "../../globalStyle";


const Navbar = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  background: ${ctaColor};
  ${mobile({ flexDirection: "row" })}`

Enter fullscreen mode Exit fullscreen mode

Voila!

That is it, short and simple. I hope it is useful for your projects.

Cheers,

Your friend,
Marizoo

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
ristenrodrig profile image
RistenRodrig

How to Create Global Styles with Styled Components? Spell to make someone move out

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more