React — css styled component
Published in
1 min readApr 6, 2022
I started to work with styled component in React and want to capture my learning here.
- First we need to install the npm package
npm i styled-components
- import
import styled, { css } from 'styled-components'
at the top
Basics
Then we can start with a simple styled button component
const Button = styled.button`
padding: 20px;
`
Extending Styles
const YellowButton = styled(Button)`
color: yellow;
`
Conditional styling in styled component
Pass parameters to the div
styled components
const Name = styled.div<{ $color?: string }>`
color: ${({ $color }) => (($color) ? $color: 'white')};
`;orconst Name = styled.div<{ $color?: string }>`
color: ${({ $color }) => ($color || 'white')};
`;
div
with default color and override with other color if it exists
const Name = styled.div<{ $color?: string }>`
color: white;
${(props) => props.$color && css`
color: ${props.$color};
`};
`;orconst Name = styled.div<{ $color?: string }>`
color: white;
${({ $color }) => $color && css`
color: ${props.$color};
`};
`;
These 4 examples return the same result, but I personally prefer to have the default css value and override with other value if conditions are met. The readability looks better.