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
Step 02.
- Inside the src folder: create a file, and call it
globalStyle.js
- Here is a 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} } `; };
- 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" })}`
Voila!
That is it, short and simple. I hope it is useful for your projects.
Cheers,
Your friend,
Marizoo
Top comments (1)
How to Create Global Styles with Styled Components? Spell to make someone move out