Spreading Props on DOM elements

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

The bad way

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

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

The good way

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

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

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

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

Notes

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

Last updated

Was this helpful?