emotion icon indicating copy to clipboard operation
emotion copied to clipboard

@emotion/styled: Add Transient Props

Open petermikitsh opened this issue 4 years ago • 57 comments
trafficstars

The problem

In 5.1.0, styled-components introduced transient props. Props prefixed with a dollar sign ($) are "mark[ed] as transient and styled-components knows not to add it to the rendered DOM element or pass it further down the component hierarchy".

Proposed solution

This would be useful functionality to support -- I am exploring migrating from styled-components to @emotion/styled.

Alternative solutions

None suggested. The intent is to follow this implementation detail introduced by another CSS-in-JS project.

Additional context

Material UI v4 -> v5 is migrating to emotion, and my project uses styled-components today. I'm trying to get my codebase to coalesce around a single CSS in JS solution, and the fewer the API differences there are, the lower the barrier to migration is.

petermikitsh avatar Dec 25 '20 04:12 petermikitsh

I'm not super keen about it but we also maintain compatibility with SC (unless we feel strongly that it's not worth it) so it might be worth adding support for this. @mitchellhamilton thoughts?

Andarist avatar Dec 25 '20 09:12 Andarist

I'm also not super keen. For migration purposes, you could have a wrapper around styled that implements it with shouldForwardProp.

we also maintain compatibility with SC (unless we feel strongly that it's not worth it) so it might be worth adding support for this

This isn't totally true. We don't have .attrs, .withConfig, createGlobalStyle, the as prop is forwarded by default for non-dom element types, css is eagerly evaluated and there are probably some other subtle differences. I think that anything you can do in s-c, there should be an equivalent way to do in Emotion, if it's not the exact same API though, that's fine.

emmatown avatar Jan 05 '21 07:01 emmatown

More context on the rationale for why the $-prefix can be useful (emphasis added):

Think of transient props as a lightweight, but complementary API to shouldForwardProp. Because styled-components allows any kind of prop to be used for styling (a trait shared by most CSS-in-JS libraries, but not the third party library ecosystem in general), adding a filter for every possible prop you might use can get cumbersome.

Transient props are a new pattern to pass props that are explicitly consumed only by styled components and are not meant to be passed down to deeper component layers. Here's how you use them:

 const Comp = styled.div`
   color: ${props => props.$fg || 'black'};
 `;

 render(<Comp $fg="red">I'm red!</Comp>);

It's presented primarily as quality-of-life, developer-experience type improvement (though I'd imagine the value of it is certainly subjective).

Additionally, styled components discusses forwarding more here (I believe this part aligns with Emotion):

If the styled target is a simple element (e.g. styled.div), styled-components passes through any known HTML attribute to the DOM. If it is a custom React component (e.g. styled(MyComponent)), styled-components passes through all props.

https://styled-components.com/docs/basics#passed-props

Emotion's current prop-forwarding is summarized as:

By default, Emotion passes all props (except for theme) to custom components and only props that are valid html attributes for string tags. You can customize this by passing a custom shouldForwardProp function. You can also use @emotion/is-prop-valid (which is used by emotion internally) to filter out props that are not valid as html attributes.

https://emotion.sh/docs/styled#customizing-prop-forwarding

The suggested workaround is a wrapper, which could look roughly something like this (if the thinking is incorrect here, please feel free to elaborate):


import styled from '@emotion/styled';

export const StyledEmotionInterop = (component: string | React.Component, template: string) => {
  return styled(component, {
    shouldForwardProp: (prop: string) => !prop.startsWith('$')
  })(template);
}

I'd like to hear more about the specifics of the concerns (e.g., is there a weak or strong objection to the implementation detail). Thanks!

petermikitsh avatar Jan 05 '21 19:01 petermikitsh

One downfall of using a wrapper function: When the styled tag is picked up by Emotion's babel autoLabel, the [local] name generated will be the name of the wrapper function (StyledEmotionInterop in the above case), and not the component defined.

jmca avatar Jan 23 '21 19:01 jmca

This is the pattern I have been using successfully with Material UI:

export const transientOptions: Parameters<CreateStyled>[1] = {
  shouldForwardProp: (propName: string) => !propName.startsWith('$'),
};
const SomeComponent = styled(
  Typography,
  transientOptions,
)<{ $customProp: boolean }>(({ theme, $customProp }) => ({...}));

Note that the shouldForwardProp will apply to components that extend the root component:

const AnotherComponent = styled(
  SomeComponent  /* no need to pass transientOptions again */
)<{ $customProp2: boolean }>(({ theme, $customProp2 }) => ({...}));

The downfall is that it is opt-in (you have to explicitly use transientOptions), at least on the root component.

jmca avatar Jan 23 '21 20:01 jmca

When the styled tag is picked up by Emotion's babel autoLabel, the [local] name generated will be the name of the wrapper function (StyledEmotionInterop in the above case), and not the component defined.

I'm not sure if that's totally correct - you should be able to utilize importMap to make labels behave pretty much the same as with the "builtin" styled.

Andarist avatar Jan 23 '21 22:01 Andarist

Oh nice. I actually didn't even know that existed. Guess I should look at those docs more šŸ˜…

jmca avatar Jan 23 '21 22:01 jmca

@Andarist Could you give an example of importMap's usage? The docs are a bit brief.

jmca avatar Jan 23 '21 23:01 jmca

https://github.com/emotion-js/emotion/blob/fa977675e1df05f210005ccd3461d6cdaf941b42/packages/babel-plugin/tests/import-mapping/import-mapping.js#L9-L38

Andarist avatar Jan 24 '21 00:01 Andarist

@Andarist How does this apply to relative imports within the same codebase?

Say a file in the same codebase defines and exports a styled wrapper function. Then another file (in the same codebase) imports that file via relative import path. How would one configure importMap to make sure that wrapper function doesn't "steal" the auto-label?

jmca avatar Jan 24 '21 03:01 jmca

Well - I would recommend creating a package for your own styled wrapper so you could configure a single entry for the importMap. Relative paths makes things worse - although you could copy the same thing with different paths leading to your styled from your app..

How would one configure importMap to make sure that wrapper function doesn't "steal" the auto-label?

I don't think it should steal it - but it might add an unnecessary label in this case. You could configure Babel to ignore the file with styled wrapper so it wouldn't happen. Wrapping in a package would also make it easier.

Andarist avatar Jan 24 '21 10:01 Andarist

@Andarist Thanks for the suggestion. Too bad importMap doesn't support regex.

jmca avatar Jan 24 '21 13:01 jmca

I'd like to hear more about the specifics of the concerns (e.g., is there a weak or strong objection to the implementation detail). Thanks!

It's mostly around the fact that it creates a distinction between "styled components" and "regular components" with the naming scheme when whether something is a styled component or not should just be an implementation detail. We also try to maintain that styled(SomeStyledComponent) is practically equivalent to styled(forwardRef((props, ref) => <SomeStyledComponent {...props} ref={ref} />))(which iirc we do with the exception of withComponent) but you would likely want to make that not true for transient props(and it isn't with SC: https://codesandbox.io/s/muddy-surf-ihu6e) which we'd like to avoid.

emmatown avatar Jan 27 '21 01:01 emmatown

This is the pattern I have been using successfully with Material UI:

export const transientOptions: Parameters<CreateStyled>[1] = {
  shouldForwardProp: (propName: string) => !propName.startsWith('$'),
};
const SomeComponent = styled(
  Typography,
  transientOptions,
)<{ $customProp: boolean }>(({ theme, $customProp }) => ({...}));

Note that the shouldForwardProp will apply to components that extend the root component:

const AnotherComponent = styled(
  SomeComponent  /* no need to pass transientOptions again */
)<{ $customProp2: boolean }>(({ theme, $customProp2 }) => ({...}));

The downfall is that it is opt-in (you have to explicitly use transientOptions), at least on the root component.

Hi,

just I want to say that I have used this solution and works great. Would be an option to add a helper function exportable from Emotion and thats all? It can be maybe customizable with a regex pattern maybe?

sauldeleon avatar Jun 21 '21 07:06 sauldeleon

has there been any progress on this or any changes of opinion if it should be done? this is really needed for DX, plus styled-components API parity...

callmeberzerker avatar Oct 05 '21 01:10 callmeberzerker

The API parity with Styled Components is not a goal. The mentioned concerns expressed here are still very much true. It also doesn't seem like there are a lot of people looking for this functionality since this thread isn't that busy at the end (I would probably have expected it to be much more busy based on this being in SC and all). This also has an impact on our consumers and I would be wary about including support for this in the current major version.

Andarist avatar Oct 05 '21 11:10 Andarist

I also just started using emotion instead of styled-components and this is the first inconvenience that I encountered. I really hope that emotion will start using $ for transient props like styled-components in order to make devs life easier. It's just uncomfortable and ugly to pass shouldForwardProp to styled all the time.

AlexSapoznikov avatar Oct 07 '21 17:10 AlexSapoznikov

@Andarist i guess people don't reply on old topics, and some people don't even know its existence in SC.

At first i was also not bothered, thought about the nasty wrapper and thought i dont want to leave my code like this. So when i used styled components it was easy to understand what props should not be added to the component. Now i did use the same pattern and all of a sudden i have to change prop hasImage:boolean into hasimage:string since in the end it expects them to be DOM attributes which they are not.

I can understand this can be breaking by people using a $props convention (who on hell, but yes Maybe) for wanting them up to the dom. So maybe it should be in the next major? But please make our lives a little more easier :)

maapteh avatar Oct 26 '21 14:10 maapteh

Note that we conditionally forward props to the underlying DOM elements (this can be customized with shouldForwardProp). If your hasImage gets forwarded then it's probably because you are wrapping a custom component with styled and you don't set its shouldForwardProp correctly (or just because you are spreading all received props onto the host element).

Andarist avatar Oct 26 '21 19:10 Andarist

A lot of people new to frontend code get bitten by this, rest spreading a bunch of props on a styled component, only to notice way to late that suddenly there are a bunch of additional properties on the HTML tag making it invalid, render ugly or other horrible things.

Transient props is an elegant solution, yea sure you can already do it now but its not convenient, passing around the same function for every styled component. Indeed since v5 release of material UI I expect a lot more people will get bitten by this eventually

JanStevens avatar Nov 02 '21 17:11 JanStevens

A lot of people new to frontend code get bitten by this, rest spreading a bunch of props on a styled component, only to notice way to late that suddenly there are a bunch of additional properties on the HTML tag making it invalid, render ugly or other horrible things.

Transient props is an elegant solution, yea sure you can already do it now but its not convenient, passing around the same function for every styled component. Indeed since v5 release of material UI I expect a lot more people will get bitten by this eventually

Exactly, and I don't understand the resistance to implement this functionality. This is the only real reason why I am still using styled-components (or mui-styled-engine-sc) vs the default engine in [email protected] which is emotion.

I don't wanna be bothered to create:

const TabsStyled = styled(MuiTabs, {
  shouldForwardProp: prop =>
    isPropValid(prop) && prop.startsWith('$')
})`
   color: ${props =>
    props.$myCustomVariantThatStartsWithDollarSign ? 'hotpink' : 'turquoise'};

`

And the last thing I need is yet another styled import (wrapper) in my codebase (babel-macros also don't work if the files are imported from elsewhere, but don't quote me on that). I currently have this issue on my watchlist but I would want clear indication from emotion team if they would add this, or we should just settle on using styled-components if we want this kind of functionality out of the box.

callmeberzerker avatar Nov 02 '21 20:11 callmeberzerker

Hi @callmeberzerker I agree with you that this is a very shitty way, but it can be improved like

import { transientOptions } from '@utils'

// just an example of a $property, thought it does not make so much sense this way lol
interface StyledProps {
  $darkTheme: boolean
}

export const MyComponent= styled('div', transientOptions)<StyledProps>`
  background-color: var(--surface-${props => props.$darkTheme});

having in some common file

import { CreateStyled } from '@emotion/styled'

export const transientOptions: Parameters<CreateStyled>[1] = {
  shouldForwardProp: (propName: string) => !propName.startsWith('$'),
}

Yes, it would be better with a default built in approach for emotion, but for the moment I use this way, and the code does not look too messy!

Original solution in this thread by @jmca

sauldeleon avatar Nov 02 '21 23:11 sauldeleon

Thank you @jmca in my case im using a third party UI library Chakra-UI and i now can prevent props from passing and throwing errors to me (prop needs to be lowerCase, value must be String etc). Codebase became much better now :)

Screenshot 2021-11-03 at 09 33 25

I still hope it will be made available in the core of Emotion.

maapteh avatar Nov 03 '21 08:11 maapteh

I've recently migrated a project I'm working on to MUI v5 and started using emotion for the first time. Came to this thread after noticing an error about receiving a boolean value for a non-boolean attribute and was hoping for a neat solution to deal with it. Came across this for styled-components, and was hoping for similar functionality for emotion. I echo the sentiments of others who don't want to have to explicitly filter out props that we don't want to pass to the DOM.

WIH9 avatar Nov 04 '21 15:11 WIH9

I came to this thread from the same SC issue as @WilliamHoangUK, having needed transient props for the first time after moving to MUI v5. Having some sort of built-in solution would be preferable to the various workarounds.

For now, I'm just passing 1 or 0 for a boolean filled prop, which suppresses the warning, but does cause a filled="1" attribute to show up on the DOM element. Unsightly, but the easiest solution for this one case.

fwextensions avatar Dec 30 '21 01:12 fwextensions

We were using css-in-js, we were passing props to styles that were only meant to affect styles.

When we try to move to @emotion, this is one of the first real annoyance. I was already thinking about creating a filter to not forward any props prefixed with some tag. Were hoping it could applied globally.

Did not know about SC transiantProps but obviously I think its a great feature that is badly missing from emotion.

For now we'll create the re-usable transientOptions as explained further up, and apply it on-the-go for each component that need "style-only related props"

Hopefully @emotion will come up with an out-of-the-box way of doing this.

Ethorsen avatar Jan 13 '22 14:01 Ethorsen

I'll try to evaluate once again if this is something that we'd like to implement. Note that you can also just wrap @emotion/styled in a custom package and just import styled from it (where that custom package should have that custom filter builtin into it). With such a solution this shouldn't be that big of an annoyance as your codebase would just have to use a different import - and all the "call sites" would benefit from it.

Andarist avatar Jan 14 '22 09:01 Andarist

Implementing a custom wrapper is a bit of a hack and its non obvious as a solution. This is an absurdly common problem. The current solutions as implemented using filter functions do not really account for the size of this issue. Unless I’m writing styles that are bespoke to me, I almost always have to pass a prop for some condition to styles, meaning I will have to implement this function the majority of the time.

jamesmfriedman avatar Jan 21 '22 11:01 jamesmfriedman

Transient props would be appreciated.

v1kt0r1337 avatar Jan 24 '22 09:01 v1kt0r1337

I really would love transient props implemented

0xalmanac avatar Feb 06 '22 21:02 0xalmanac