What are styled-components?
Styled Components allow you to style your App through individual React components.
Learn more with the offical docs: Offical Docs
How to install styled-compoents?
You can install styled components like any other Node Package!
npm install --save styled-components
yarn add styled-components
Once you import styled-components into your project, you are free to style your components however you like. The clever thing about styled-components is that you are creating normal reusable components, with your styles attached to them.
How to use styled-components?
When using styled-components, you dont need to worry about class names, or stylesheets. The styles live in the component files, and can be called and used just like any other JSX.
Below, you can see the H1 variable is just a styled h1 tag, using a template literal. Plain CSS is inside the template literal.
import "./styles.css";
import styled from "styled-components";
const H1 = styled.h1`
font-family: Ariel;
font-size: 56px;
color: blue;
`;
export default function App() {
return (
<div className="App">
<H1>Hello World</H1>
</div>
);
}
Here is the rendered H1 component.
Now that we know how to create a styled component, lets use the power of JavaScript to really customize some components. I am talking about styling buttons using props!
Being able to use props in styled components gives you the ability to create multiple buttons without having to create a bunch of CSS classes.
There is a primary prop, which sets the color of the button, and the big prop, which changes the size of the button.
import "./styles.css";
import styled from "styled-components";
const Button = styled.button`
background: ${(props) => (props.primary ? "Blue" : "white")};
color: ${(props) => (props.primary ? "white" : "Blue")};
font-size: ${(props) => (props.big ? "2em" : "1em")};
margin: 1em;
padding: 0.25em 1em;
border: 2px solid Blue;
border-radius: 3px;
`;
export default function App() {
return (
<div className="App">
<Button primary>Button 1</Button>
<Button big>Button 2</Button>
<Button big primary>
Big Primary Button
</Button>
</div>
);
}
The props can be used on the same button to create unique components without having to create another component in your app.
Here is the project:
I look forward to seeing what you create using styled-components. š