This is my memo for using styled-components.
Basic syntax
import styled from "styled-components"
const StyleContainer = styled.cssSelector`
// your styles
`
This is the example for styling a button.
const BaseButton = styled.button`
padding: 10px;
background-color: #333;
color: white;
border-radius: 20px;
border: none;
cursor: pointer;
`;
Use props
Since this is JS, you can pass props.
This is the example to leverage this feature to share same stylings but change background color depending on the page number.
export const PageContainer = styled.div`
min-height: 100vh;
background-color: ${(props) => props.color};
color: white;
padding: 10px;
`;
Use this component with a color prop.
import { PageContainer } from "./Page.style"
const Page2 = () => {
return (
<PageContainer color="#5bb381">
<h1>Page2</h1>
</PageContainer>
);
};
export default Page2;
Use custom components
You can style other components as well as css selectors.
This code snippet uses Link from react-router-dom.
const LogoContainer = styled(Link)`
text-decoration: none;
${linkStyle}
`;
I will tell the wired syntax ${linkStyle} later.
You can use other style components to extends the styling.
const BaseButton = styled.button`
padding: 10px;
background-color: #333;
color: white;
border-radius: 20px;
border: none;
cursor: pointer;
`;
const SecondaryButton = styled(BaseButton)`
background-color: white;
border: 1px #333 solid;
color: #333;
`;
Create reusable variable
We can have JS variables as css variables. The basic syntax is create JS variables and wrap it around with ${} when you use it.
const blue = "blue";
const LinkContainer = styled(Link)`
${linkStyle}
&:hover {
color: ${blue};
}
`;
Create reusable css snippets
You can create css snippets similar to @maxin in scss.
const black = "black";
const linkStyle = css`
color: ${black};
cursor: pointer;
`;
const LogoContainer = styled(Link)`
text-decoration: none;
${linkStyle}
`;
The whole code is available here.
The original article is here
Top comments (1)
Happy learning I really enjoy using styled-components. It has so many advantages over pure css.