styled components and template literals deep dive

We did not use styled components at my last job but am using it now in personal projects. css in js feels as weird as html in js did when I first encountered react. But I see how it solves some css issues and can allow sophisticated constructs for styling components.

styled-components makes use of tagged template literals. Normally when we use template literals we just use the string formatter string interpolation (create strings using substitution)  e.g. `Welcome ${user.name}`

When we use that form we're actually using a default function (which does string interpolation for us). But you can supply your own custom function and call like so:

myTemplateFn`Welcome ${user.name}`

The template literal is passed to your "tagged function" myTemplaetFn...but as an array (for strings) and separate param for each placeholder (each dollar sign and curlies). It's the same as:

myTemplateFn(['Welcome'], "jane")

where user.name contains "jane"

This is standard ES6 tech which styled-components (and emotion) uses. 

You can also include interpolated functions inside template literals like so:

myTemplateFn `Welcome ${() => user.name}`

...myTemplateFn would need to check for a fn passed and call it to get the value

Here's an example of myTemplateFn

const myTemplateFn = (strings, ...args) => {
args.forEach(arg => {
if (typeof arg === 'function') {
console.log(arg());
}
})
}

which could be called like so

myTemplateFn`this is a ${p1} template and ${() => p2} alright`;


styled-components 

  • adds helper functions such as styled.h1 or styled.button to create those html elements and accept template literals
  • handles executing any interpolated functions passed
  • passes props through to your interpolated function so you can references them and write logic based on props

There's lots of online explanations of how this is done by styled-components, this is a good one by Max S. and another here by Eugene

Checkout the styled-components code here where it sets up all the dom elements on styled as functions, so we can call like so styled.div``
That setup calls constructWithOptions which creates its own templateFunction that takes as 2nd arg the interpolations (like our simple myTemplateFn above). Then calls createStyledComponent to create a function for each tag

styled-components library is sophisticated code especially including all the complex typescript typings.


Best Practices for using
  • using a reset: can be done using one of the styled resets
  • global variables: define values in json and import into react components
  • thinking differently: basically everything with styles (e.g. a div with className) becomes a styled component (as opposed to a css class in another file)




 



Comments

Popular posts from this blog

deep dive into Material UI TextField built by mui

angular js protractor e2e cheatsheet

react-router v6.4+ loaders, actions, forms and more