Styled-components is CSS-in-JS styling framework in react. There are many advantages of using Styled components so before jumping into it directly let’s see some advantages of it .
Why Styled Components?
- CSS class name Bugs – Writing plain CSS in react using classnames can cause unexpected overwrite or duplications but Styled component generates unique classes for defined style.
- Reusable – Like normal react component you can create reusable components like button, forms, tables, sections, etc hence avoid duplication of code.
- Dynamic Styling – Using props you can do dynamic styling again avoids duplication of styles.
- Writing pure CSS – you can write pure CSS inside styled component. So no more styles as a javaScript objects as it is in other styling solutions in react.
- Performace – This framework is very smart. It doesn’t loads all styles at once but only loads the rendered component styles.
Installation
Let’s install styled components in your React App –
# with npm npm install --save styled-components # with yarn yarn add styled-components
Once the library is installed you need to import styled from styled-component package just like this
import styled from "styled-components";
In styled components you don’t need to write styles as an object inside jsx components instead it uses tagged template literarals in JS which provides power to use plain CSS inside JS for react component.That style get attached to defined component itself.
Creating a component
So let’s start with creating a button-
import styled from "styled-components"; const Button = styled.button` margin:10px; padding: 5px 10px; border: 2px solid green; border-radius: 3px; color:green; ` // Utilizing above Button Component <Button>Click</Button> <Button>Click</Button> <Button>Click</Button>
We can create as many button components as we want by just duplicating it. Superb right ? . But of course we generally don’t want only one type of button for our dream websites.
Website