DEV Community

Cover image for ReactJS Anti Pattern ~Spreading props directly onto DOM elements~
Ogasawara Kakeru
Ogasawara Kakeru

Posted on

ReactJS Anti Pattern ~Spreading props directly onto DOM elements~

・Spreading props directly onto DOM elements can indeed lead to the addition of unknown HTML attributes.

const Sample = () => (

    <Spread flag={true} className=content />

  );

  const Spread = (props) => (

    <div {props}>Test</div>

  );
Enter fullscreen mode Exit fullscreen mode

The spread component is spreading all props onto the

element without filtering them. And we know that has no attribute called flag in its definition.

If any unrecognised HTML attributes are included in the props passed to spread, they will be added to the rendered DOM element. This can lead to unexpected behaviour or errors, as unknown HTML attributes may not be handled correctly by React or the browser.

The better approach is to create props specially for the DOM attribute.

const Sample = () => (

    <Spread flag={true} domProps={{className: content}} />

  );

  const Spread = (props) => (

    <div {props.domProps}>Test</div>

  );

Top comments (0)