styled-components

  • How they work

  • Best practices

  • New features & API changes

s-c work because of tagged template literals 

Tagged templates allow you to parse template literals with a function.

 

The first argument is an array of string literals, and the following arguments are the interpolations.

behind the scenes: tagged template literals

behind the scenes: lifecycle

3. Create a React Component from the BaseStyledComponent

class

 2. Inject a marker into the stylesheet

1. Create a counter & unique ID for the component

behind the scenes: lifecycle

4. Inject into stylesheet

best practices: component architecture

Use the single responsibility principle

The single responsibility principle is a computer programming principle that states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

Identify the discrete UI states the component needs to satisfy

Consider Reusability

1. Very specific use case?

2. App specific use cases?

3. Completely generic and reusable? (Can be used in any context)

Try to keep props state-oriented. Avoid adding props that shadow CSS properties.

best practices: IRL

state = {
    todos: []
    todoLength: 0
}

Style declarations should be "derived" from UI state

1. Use inline styles

2. Extend the component

best practices: IRL

Use inline styles or s-c's built in styled() function for minor tweaks

Avoid nested ternaries

best practices: IRL

Document props with PropTypes

best practices: IRL

Use styled() to extend styles of 3rd-party components

(as long as props are passed through)

best practices: IRL

Take advantage nested rules

best practices: IRL

Use the .attrs() helper to pass props

👎

best practices: IRL

👍

Define s-c outside of the render method

👎

👍

best practices: IRL

  • babel-plugin-styled-components

    • server side rendering
    • minification
    • adds displayName to class for better debugging
  • jest-styled-components

    • snapshot testing
    • toHaveStyleRule()
  • vscode-styled-components

    • syntax highlighting
  • stylelint-config-styled-components

    • ​linting

best practices: tooling

styled-components@4.0.0: what's new

  • createGlobalStyle API

    • replacement for .injectGlobal
  • "as" prop

    • replacement for .withComponent()
  • deprecated Comp.extend

  • deprecated innerRef

  • StrictMode compliance for React 16

    • dropping support for React 15 and below

styled-components

By Kaitlin Moreno

styled-components

  • 1,082