Spreading properties on DOM elements

There is a common practice that has recently been described as an anti-pattern by Dan Abramov; it also triggers a warning in the console when you do it in your React application.

It is a technique that is widely used in the community and I have personally seen it multiple times in real-world projects. We usually spread the properties to the elements to avoid writing every single one manually, which is shown as follows:

  <Component {...props} />

This works very well and it gets transpiled into the following code by Babel:

  React.createElement(Component, props);

However, when we spread properties into a DOM element, we run the risk of adding unknown HTML attributes, which is bad practice.

The problem is not related only to the spread operator; passing non-standard properties one by one leads to the same issues and warnings. Since the spread operator hides the single properties we are spreading, it is even harder to figure out what we are passing to the element.

To see the warning in the console, a basic operation we can do is render the following component:

  const Spread = () => <div foo="bar" />;

The message we get looks like the following because the foo property is not valid for a div element:

Unknown prop `foo` on <div> tag. Remove this prop from the element

In this case, as we said, it is easy to figure out which attribute we are passing and remove it but, if we use the spread operator, as in the following example, we cannot control which properties are passed from the parent:

  const Spread = props => <div {...props} />;

If we use the component in the following way, there are no issues:

  <Spread className="foo" />

 This, however, is not the case if we do something like the following. React complains because we are applying a non-standard attribute to the DOM element:

  <Spread foo="bar" className="baz" />

One solution we can use to solve this problem is create a property called domProps that we can spread safely to the component because we are explicitly saying that it contains valid DOM properties.

For example, we can change the Spread component in the following way:

  const Spread = props => <div {...props.domProps} />;

We can then use it as follows:

  <Spread foo="bar" domProps={{ className: 'baz' }} />

As we have seen many times with React, it's always good practice to be explicit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset