DEV Community

CamelJohn
CamelJohn

Posted on • Edited on

styled-components - avoiding transient props

so, I had this error - where the gist is that react is throwing an error that 'prop_whatever' is not a know prop (DOM wise).

this is a styled-components error in the end.

what was happening was those props where being used, in a logic layer, but, propagated to the underlying VDOM representation of a DOM element, meaning - that said props would "bleed" into the real DOM - no cool.

.withConfig to the rescue - basically a chained function exported by the good people at styled-components where one of the fields accepts some sort of filter function, to decide wether forwarding this prop will happen or not.

so here's my function:

export function preventTransientPropForwarding(prop: string) {
  return ![/anyPropYouWouldNotLikeToTransfer/].some(regEx => regEx.test(prop);
}
Enter fullscreen mode Exit fullscreen mode

and the implementation would simply look like so:

const SomeStyleComponentsComponent = styled(Extended3rdPartyComponent).withConfig({
    shouldForwardProp: (prop) => preventTransientPropForwarding(prop),
})``;
Enter fullscreen mode Exit fullscreen mode

although the API will tell you to prefix props with $ to prevent the propagation, that is still manual.

unfortunately, this is very tedious and manual.

so, here's another solution i've implemented:

basically - you will override the default styled object.


import _styled, { AnyStyledComponent, ThemedStyledFunction } from 'styled-components';

export function styled(
    element:
        | AnyStyledComponent
        | keyof JSX.IntrinsicElements
        | React.ComponentType<any>
): ThemedStyledFunction<
    typeof element,
    any,
    object,
    string | number | symbol
> {
    return _styled(element).withConfig({
        shouldForwardProp: (prop: any) => !preventPropLeak(prop),
    });
}

Enter fullscreen mode Exit fullscreen mode

now, check this out! you get auto-completion out of the box, and you can use 3rd party UI components, and extend them using your function.

the only caveat is, you will no longer be able to do something like styled.div but would rather have to conform to styled('div');

why would you do this ?

simple - I'm working with vscode, and i have the styled-components extension that allows me to write emmet css, to code faster and get some auto-completion for my css and not just for component types.

hope you liked this solution !

not my best...but still, works if you need it.

Top comments (0)