Transient Props in styled-components
How to avoid errors when passing boolean state values as custom attributes to React styled-components
Overview: Transient Props allow you to pass boolean value props to styled-components such that they do not render as an element’s attributes on the DOM. This prevents the errors and allows for some more complex use of
By preceding a component’s boolean attribute with a
styled-components will recognize that attribute as a something purely for styling rather than a usual boolean attribute like
autoplay, other boolean attributes recognized by most browsers.
Example: In a project that made a call to an API, I wanted a way to set the
display attribute of two separate elements to
flex based on the status of the call to the API. The loading state was comprised of three separate boolean state values,
loadFailed. The first and third values are relevant here. The way I thought to do this was something like this:
Unfortunately, using boolean state values as attributes hurts the browsers brain as it treats those in the same way as other boolean attributes like
required (for inputs) or
autoplay (for media). It doesn’t recognize the attribute
display, thus the error
Warning: Received `false` for a non-boolean attribute is thrown. Some people don’t like that. To work around this, tell styled-components not to render that attribute to the DOM with a
$ just before the prop name like:
This allows you to use some more complicated or concise logic to add styling to elements. Could you do this with
loading && <Element />? Yes. For sure. And in this case it would be far more concise to do that. This demonstration was a simplified version of a use case where I wanted to adjust the border of an element based on the router path, and for a few reasons beyond the scope of this long ramble it made more sense to use boolean props.
styled-components library is full of fun little features that allow for us to approach problems in slightly different ways than we’re used to. While these methods might not be better every time, it is fun to practice approaching logic with a fresh perspective. Best case, you discover more concise logic that makes more sense to you and an increase the readability of your code. Worst case, you learn something new and can carry that knowledge with you forever.