π Getting Started to use Styled Components in your React App
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.