πŸš€ Getting Started to use Styled Components in your React App

Haneen Mahdin
2 min readMar 2, 2022

You might have always a solution to write css inside your React App. Well, Today I’m gonna show you one of the most popular css-in-js libraries πŸ’… Styled Components.

Installation

You can use yarn or npm to download the package

yarn add styled-components# ornpm i styled-components

πŸ€– Creating a new component

Styled components defines all the default html elements inside it’s module. So you don’t have to re-write all the elements by yourself.

Let’s take a look at creating a simple Component.

import styled from "styled-components";const Header = styled.header`
font-size: 40px;
font-weight: bold;
color: #122;
`;
function App() {
return <Header>My awesome page 😎 </Header>;
}

Here we have created a simple Header component which defines some styles inside it’s parameters.

πŸ’¬ Passing Props to components

We can choose to render styles according to the props passed on the component. Here is a simple example which adds a padding of 20px, if the component has child components inside it:

import styled from "styled-components";const Pressable = styled.button`
padding: 0 ${props => props.children.length !== 0 && "20px"};
`;
function App() {
return (
<Header>
<h3>To-dos</h3>
<p>Create, store your notes here πŸ˜ƒ!</p>
</Header>
);
}

🧼 Using CSS to render css

You can render css styles by using the css function declared inside the styled-components. It can be very useful in some use-cases, Like creating a secondary, default, primary style variants for a component.

import styled, { css } from "styled-components";const PrimaryStyles = css`
background: #166edc;
color: #fafafa;
`;
const SecondaryStyles = css`
background: #d3d3d340;
border: 1px solid #b3b3b3;
color: #222;
`;
const CommonStyles = css`
font-weight: bold;
padding: 5px 15px;
margin: 10px 20px;
`;
const Button = styled.button`
${CommonStyles}
${p => {
switch(p.theme) {
case 'primary':
return PrimaryStyles;
case 'secondary':
return SecondaryStyles;
default:
return SecondaryStyles;
}}
`;
const MyButtonPage = () => {
return <Button theme="primary">Hello World πŸ‘‹ </Button>;
}

The above example shows how you can the css function in styled-components to create style variants. This feature can be very useful sometimes πŸ˜ƒ.

πŸ‘… Passing default attributes using .attrs callback

We can use .attrs function inside a styled component declaration to specify some default attributes that will be used by the component.

import styled from "styled-components";const CheckBox = styled.input.attrs({ checked: false })`
margin: 0 20px;
`;

And there is more stuff you can do with this awesome library 🀩 !

Get to know me more on Twitter @HaneenMahdin.

--

--

Haneen Mahdin

✢ 16, freelance design engineer and startup-founder