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
which could be called like so
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
- 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
Post a Comment