This content originally appeared on DEV Community and was authored by Yuko
This is my memo for using styled-components.
Basic syntax
Use props
Use custom components
Create reusable variable
Create reusable css snippets
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
This content originally appeared on DEV Community and was authored by Yuko
Yuko | Sciencx (2022-05-30T22:09:30+00:00) 5 basic styled-components skills I’ve learned. Retrieved from https://www.scien.cx/2022/05/30/5-basic-styled-components-skills-ive-learned/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.