styled-components / styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress 💅
https://styled-components.com
MIT License
40.46k stars 2.5k forks source link

Unknown HTML attributes passed to the DOM (v4.0.3) #2177

Closed alexandernanberg closed 5 years ago

alexandernanberg commented 5 years ago
## System:
 - OS: macOS 10.14.1
 - CPU: x64 Intel(R) Core(TM) i9-8950HK CPU @ 2.90GHz
 - Memory: 2.02 GB / 16.00 GB
 - Shell: 5.3 - /bin/zsh
## Binaries:
 - Node: 10.12.0 - ~/.nvm/versions/node/v10.12.0/bin/node
 - Yarn: 1.10.1 - /usr/local/bin/yarn
 - npm: 6.4.1 - ~/.nvm/versions/node/v10.12.0/bin/npm
## npmPackages:
 - babel-plugin-styled-components: ^1.8.0 => 1.8.0 
 - styled-components: ^4.0.0 => 4.0.3 

Reproduction

https://codesandbox.io/s/o15z2r013y

Steps to reproduce

I haven't really had time to dig down into what causes this exactly, my best guess is that it's the React.forwardRef?

Edit: Was not because of forwardRef but seems to because of React.createElement? 🤔

Expected Behavior

Unknown attributes/props should not be passed to the DOM element

Actual Behavior

Unknown attributes are added on the DOM element which causes React to log errors

kitten commented 5 years ago

This is intended behaviour :) when a component is wrapped instead of an element being used we don't filter your props.

I'd recommend you to always create element StyledComponents by default as best practice and wrap components only when necessary.

When you then wrap a component you'll have to take care of filtering props yourself.

alexandernanberg commented 5 years ago

@kitten Huh interesting... didn't know that!

What would be the best strategy if you want to exclude known props from being passed to the DOM element? Eg. <Div textAlign="center" width="50%" />

iduuck commented 5 years ago

Any update here? Don't want to create a custom component to wrap my styled-components only for filtering the props. So, what is the easiest way? My divs are spamming my source code.

vaunus commented 5 years ago

@alexandernanberg @iDuuck

If I'm understanding you both correctly, there is already a solution to this. I had to go digging in the issues to find it but it is already answered elsewhere.

See https://codesandbox.io/s/wkxq1v5ozw for amended code to your original question.

In short, you can do something like the following to avoid passing down the justifyContent prop.

const Grid = styled(({ justifyContent, ...props }) => <Tag {...props} />)({
  display: "flex",
  flexWrap: "wrap"
});