As the name itself says styled components is a component-based styling tool. It is powered by tagged templates and allows to create react components with styles.
npm install -save styled-components
import styled from 'styled-components’
I’ll show this with an example. Let’s style our website header section
<Header>
<MenuWrapper>
<MenuItem>Home</MenuItem>
<MenuItem>About</MenuItem>
<MenuItem>Contact</MenuItem>
</MenuWrapper>
<Logo>Site Name</Logo>
<HeaderRight>
<Login>Login</Login>
</HeaderRight>
<Header>
const Header = styled.header`
display: grid;
grid-template-columns: 1fr 100px 1fr;
`
const MenuWrapper = styled.nav`
position: relative
`
const MenuItem = styled.a`
color: black;
padding: 10px;
display: inline-block
`
const Logo = styled.div`
font-size: 2rem;
color: red;
`
const HeaderRight = styled.div`
text-align: right
`
const Login = styled(MenuItem)`
color: white;
max-width: 80px;
background-color: black;
`
And this will be rendered as below;
Styles will be added inside the style tag in the head
export const Colors = {
black: ‘#373436’,
gray: ‘#b1bfd0’,
white: ‘#ffffff’,
yellow: ‘#ffb721’,
red: ‘#f2405d’,
blue: ‘#5f93e7’
};
Using variables
button {
color: ${Colors.white};
background-color: ${Colors.red}
}
You must be wondering how am I going to write my global styling with styled components as this is component-based. Before you worry, the developers have provided us with createGlobalStyle function.
Using Global Style
import styled, {createGlobalStyle} from 'styled-components'FullwidthWrapperexport const GlobalStyles = createGlobalStyle`
body {
font-size: 13px;
color: black;
a {
color: blue
}
}
`
Styled components can identify values passed through attributes. For example, we can pass these <Header grid col_s={"1fr 100px 1fr"} />
This will be passed through our styles.
${props => props.grid && css`
display: grid
`};
grid-template-columns: ${ ({col_s}) => col_s ? col_s : '1fr' };
In this case, if the grid is passed through a prop, it will understand it and apply the style as display: grid
Do check out the Zen-styled component project to style your web app simply.