Spreading props on DOM elements

When we spread props we run into the risk of adding unknown HTML attributes, which is a bad practice.

Bad

This will try to add the unknown HTML attribute flag to the DOM element.

  1. const Sample = () => (<Spread flag={true} className="content"/>);
  2. const Spread = (props) => (<div {...props}>Test</div>);

Good

By creating props specifically for DOM attribute, we can safely spread.

  1. const Sample = () => (<Spread flag={true} domProps={{className: "content"}}/>);
  2. const Spread = (props) => (<div {...props.domProps}>Test</div>);

Or alternatively we can use prop destructuring with ...rest:

  1. const Sample = () => (<Spread flag={true} className="content"/>);
  2. const Spread = ({ flag, ...domProps }) => (<div {...domProps}>Test</div>);

Note

In scenarios where you use a PureComponent, when an update happens it re-renders the component even if domProps did not changed. This is because PureComponent only shallowly compares the objects.