Styled Components with React: Syntax Tips and Tricks in 2022

by Hannah Goodridge ~ 3 min read

Like this post?

00

Styled components with React: syntax tips and tricks in 2022

Although not particularly a new technology, after working with styled components for a while and jumping in to a new large codebase I've found the need for some more complex examples of styled components. Particularly with the advance use of themeing when working with components. The docs seem a little lacking in my honest opinion but that could just be because I have specific use case.

So here are some snippets I've found useful and if I manage to educate others then thats a win too.

1.Adding attributes to elements

const Btn = styled.button.attrs({ type: "button", })`

2.Adding multiple attributes to elements

Here I have a component that requires multiple attributes being set and access to the theme as colours are stored on it.

const Icon = styled(NamedIcon).attrs(theme => ({ name: 'chevron', size: 24, fill: red(800)(theme), className: 'icon icon-prmiary', }))``;

3.Adding attributes to elements with css

const Btn = styled.button.attrs({ type: 'button', })` padding: 0; margin: 0; background: transparent; border: none; `;

4.Passing props

Props can be passed to styled components just as they are with regular React components (class or functional). This is possible because styled components are actually React components.

<Button background="blue">Click Me</Button> <Text color="green">Some text in here</Text>
const Button = styled.button` padding: 2px 5px; background-color: ${props => (props.background ? props.background : 'transparent')}; border-radius: 3px; `; const Text = styled.p` padding: 10px; color: color: ${props => (props.color ? props.color : 'black')}; `;

5.Changing multiple lines of css based on a prop value inside a ternary

Let say my button could have a small variant and I want to change a few bits of css depending on it.

import styled, { css } from 'styled-components';

^ Don't forget to add the css import to styled components!

const Btn = styled.button` ${({ small }) => small ? css` display: inline-flex; padding: 0 10px; font-size: 1.2rem; ` : css` display: flex; padding: 0 20px; font-size: 1.6rem; `} `;

6.Style pseudo-selectors

const Btn = styled.button` ::before { content: ''; //other css in here } :hover { background-colour: red; } `;

7.Reassign the HTML tag that is associated

Styled components are dynamic in nature. They can change from creating and rendering one HTML element to another. Here's a couple of ways to do this.

Like this:

<Button as="a">Click Me</Button>

or like this:

const Btn = styled.button.attrs(() => ({ as: "a", }))`

8.Using object notation instead of template strings.

const Heading = styled.h1(({ small }) => ({ textAlign: 'center', fontSize: small ? 16 : 24, fontFamily: 'Helvetica, sans-serif', }));

The sky is the limit with styled components, hopefully these tips helped you!

Thanks for reading :)