emotion-js / emotion

šŸ‘©ā€šŸŽ¤ CSS-in-JS library designed for high performance style composition
https://emotion.sh/
MIT License
17.51k stars 1.11k forks source link

@emotion/styled: Add Transient Props #2193

Open petermikitsh opened 3 years ago

petermikitsh commented 3 years ago

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.

Andarist commented 3 years ago

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?

emmatown commented 3 years ago

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.

petermikitsh commented 3 years ago

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!

jmca commented 3 years ago

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 commented 3 years ago

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.

Andarist commented 3 years ago

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.

jmca commented 3 years ago

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

jmca commented 3 years ago

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

Andarist commented 3 years ago

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

jmca commented 3 years ago

@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?

Andarist commented 3 years ago

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.

jmca commented 3 years ago

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

emmatown commented 3 years ago

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.

sauldeleon commented 3 years ago

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?

callmeberzerker commented 3 years ago

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...

Andarist commented 3 years ago

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.

AlexSapoznikov commented 3 years ago

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.

maapteh commented 3 years ago

@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 :)

Andarist commented 3 years ago

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).

JanStevens commented 3 years ago

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

callmeberzerker commented 3 years ago

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 material-ui@5.x 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.

sauldeleon commented 3 years ago

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

maapteh commented 3 years ago

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.

WIH9 commented 3 years ago

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.

fwextensions commented 2 years ago

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.

Ethorsen commented 2 years ago

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.

Andarist commented 2 years ago

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.

jamesmfriedman commented 2 years ago

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.

v1kt0r1337 commented 2 years ago

Transient props would be appreciated.

0xalmanac commented 2 years ago

I really would love transient props implemented

julianoappelklein commented 2 years ago

I have a solution which is working very well for me.

I wrapped the styled instance returned by emotion to extend it. The extension basically adds a default shouldForwardProp, so you don't need to set it on every component you are extending.

See the solution below. Keep in mind I'm using Typescript, but adapting it to pure JS should be fairly easy.

transient-styled.ts:

import _styled from '@emotion/styled';

const styled = ((component: any, config: any) => {
  config = { shouldForwardProp: (prop: string) => !prop.startsWith('$'), ...config };
  return _styled(component, config);
}) as (typeof _styled);

const tags = 'a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|marquee|menu|menuitem|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|picture|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr|circle|clipPath|defs|ellipse|foreignObject|g|image|line|linearGradient|mask|path|pattern|polygon|polyline|radialGradient|rect|stop|svg|text|tspan'.split('|');
for(const tag of tags){
  (styled as any)[tag] = styled(tag as any);
}

export default styled;

Then you just have to import and use it:

import styled from './transient-styled';

const MyComponent = styled.div<{$isRed: string}>`
  ${p => p.$isRed ? 'color: red;': undefined}
`;

I'm using it on a project that we recently migrated from styled-components to emotion and the warnings are gone.

This could easily become a tiny npm package.

jmca commented 2 years ago

@julianoappelklein That is a valid approach, but a couple hiccups with Babel + some workarounds mentioned at:

julianoappelklein commented 2 years ago

Thanks @jmca - I see you mentioned earlier that this solution (and similars) will generate different labels.

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.

I confess I don't understand the implications of this. I'm not seeing any side effect in our project. Can you elaborate more?

xenostar commented 2 years ago

I just switched a project from styled-components to emotion and have run into this issue within minutes after switching. Transient props feels like a must, and this feels like a major inconvenience. Creating wrapper exports or injecting extra functions/objects into every component that needs this is quite frankly absurd for a solution. Emotion should be a pleasure to use right out of the box, I shouldn't have to jump through all these hoops to do something as simple as pass props around.

pkaufi commented 2 years ago

I agree that having this implemented would make my life much easier. We're also just in process of migrating from SC to emotion, and this is a huge pain point. If you don't want to support it out of the box, maybe a configuration could be added, where it's possible to add a default behaviour for shouldForwardProp?

jongbelegen commented 2 years ago

I agree that having this implemented would make my life much easier. We're also just in process of migrating from SC to emotion, and this is a huge pain point. If you don't want to support it out of the box, maybe a configuration could be added, where it's possible to add a default behaviour for shouldForwardProp?

I also would prefer overwriting the default behavior for shouldForwardProp, maybe through provider context or instance creation. We could document a clean way of having "styled-components" like transient props in emotion with this approach.

My case is totally different, I don't want SVG props to be passthrough in my normal components. I have styled-components with options like color, spacing etc. and I prefer just disabling all svg passthroughs.

mbcod3 commented 2 years ago

Why does emotion forward boolean prop to dom element by default? If it doesnt big use case for transient props would be resolved.

sshmaxime commented 2 years ago

I use Material UI (MUI) and it took me quite some time to realize that it was coming from emotion (being the default UI engine of MUI). I had to change the UI engine of MUI back to Styled-Component. This is how to do it: https://mui.com/material-ui/guides/styled-engine/#how-to-switch-to-styled-components

fxdave commented 2 years ago

When I create an interface for an element:

interface DivProps {
   big: boolean
}

It means I don't want its props for the HTML element

const StyledDiv = styled('div', {
   shouldForwardProp: (prop) => prop !== 'big'
})<DivProps>({
   // ...
})

So, ideally, I would have to write this:

const StyledDiv = styled.div<DivProps>({
   // ...
})

To be honest, this library is messing two different sets of props together, and we are trying to split them up manually. It's like the inheritance coding habit that messes two schemas together, which I and I hope others as well don't like. We can solve that by using composition that gives names to the different schemas. And the solution is simple here as well:

The definition stays this untouched:

interface DivProps {
   big: boolean
}
const StyledDiv = styled.div<DivProps>({
   // ...
})

However the usage will be different. There are 3 solutions: The cleanest solution:

<StyledDiv elementProps={{ className: "something" }} styledProps={{ big: true }} /> 

With a dedicated elementProps:

<StyledDiv big={true} elementProps={{ className: "something" }} /> 

Or with a dedicated styledProps which would be strange for a WrapperComponent like StyledDiv:

<StyledDiv className="something" styledProps={{ big: true }} /> 

Side note: In languages like Rust there would be no other solution. You would have to go with the first one, unless you want to copy the props from the elementProps and the styledProps to a new struct, which would be a maintenance hell. Unfortunately JS allows these evil solutions like which we have now.

KevinKra commented 2 years ago

TLDR emotion will probably never add this feature šŸ‘ŽšŸ»

Monstarrrr commented 2 years ago

As a more junior developer this is holding me back quite a lot for something as basic and important as passing props around.

Nantris commented 2 years ago

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

@Andarist I feel like this should be revisited, even if there's not a clear path forward. It's by far the most thumbs-upped issue on the tracker at this point with 51 currently - more than double the next highest.

Ethorsen commented 2 years ago

We all hope that some sort of mechanism will be implemented to help alleviate this problem. But after a few years, it just feels like the dev team wont do anything about it

AlexSapoznikov commented 2 years ago

Was getting another check on this thread after Oct 7, 2021. It's sad that this is still a problem, so avoiding emotion-js this time.

Nantris commented 2 years ago

8 more thumbs-ups since my last comment about 75 days ago.

ndeviant commented 1 year ago

Any updates on this?

mlnarik3pg commented 1 year ago

We would like to see this feature!

MadPeachTM commented 1 year ago

so, it has been 2 years since the start of this conversation... has emotion implemented this feature? Docs on their website don't work and i can't find an answer anywhere

Ethorsen commented 1 year ago

@MadPeachTM Most probably not

answer is right here, simple JS version (there are TS examples in the thread):

export const withTransientProps = {
  shouldForwardProp: (propName) => propName !== 'theme' && !propName.startsWith("$"),
};

Then add it when necessary

const MyStyledStuff = styled(Stuff, withTransiantProps)(({ $someTransiantProp }) => ({
}));
ghost commented 1 year ago

Any plans to add this?