|
| 1 | +--- |
| 2 | +id: spreading-props-on-dom-elements-is-an-anti-pattern |
| 3 | +sidebar_label: Spreading props on DOM elements is an anti-pattern |
| 4 | +title: Spreading props on DOM Elements is an Anti-pattern |
| 5 | +description: spreading props on DOM elements is an anti-pattern | React Patterns, techniques, tips and tricks in development for Ract developer. |
| 6 | +keywords: ['shouldComponentUpdate avoid heavy re-renders', 'reactpatterns', 'react patterns', 'reactjspatterns', 'reactjs patterns', 'react', 'reactjs', 'react techniques', 'react tips and tricks'] |
| 7 | +version: Spreading props on DOM elements is an anti-pattern |
| 8 | +image: /img/reactpatterns-cover.png |
| 9 | +--- |
| 10 | + |
| 11 | +Well, we usually spread the properties to the elements to avoid writing every single one manually. |
| 12 | + |
| 13 | +```jsx |
| 14 | +<Component {...props} /> |
| 15 | +``` |
| 16 | + |
| 17 | +This works very well, however, when we spread props into a Dom element, we run the risk of adding unknown HTML attributes, which is a bad pratice. |
| 18 | + |
| 19 | +To see the warning in the console, a basic operation we can do is render the following component. |
| 20 | + |
| 21 | +```jsx |
| 22 | +const Spread = () => <div foo="bar" /> |
| 23 | +``` |
| 24 | + |
| 25 | +The message we get looks like the following. |
| 26 | + |
| 27 | +```jsx |
| 28 | +Unknown props `foo` on <div> tag. Remove this prop from the element |
| 29 | +``` |
| 30 | + |
| 31 | +Because the foo property is not valid for a div element. |
| 32 | + |
| 33 | +In this case, as we said, it's easy to figure out which attribute we are passing and remove it but, if we use the spread operator, as in the following. |
| 34 | + |
| 35 | +```jsx |
| 36 | +const Spread = props => <div {...props} /> |
| 37 | +``` |
| 38 | + |
| 39 | +We can't control which properties are passed from the parent. |
| 40 | + |
| 41 | +If we use the component in the following way, there are no issues. |
| 42 | + |
| 43 | +```js |
| 44 | +<Spread className="foo" /> |
| 45 | +``` |
0 commit comments