React Fragment Syntax for Efficient List Rendering

Most React devs know the shorthand fragment syntax: <> </> Clean. No extra DOM nodes. Love it. But here's the catch. It doesn't accept props. So when you're mapping over a list and need to add a key, this won't work: posts?.map(post => (  <>   <PostTitle title={post.title} />   <PostBody body={post.body} />  </> )) React needs that key to efficiently track and update list items. Without it, you'll get warnings and potential rendering bugs. The fix? Use the full Fragment syntax: import { Fragment } from 'react'; posts?.map(post => (  <Fragment key={post?.id}>   <PostTitle title={post?.title} />   <PostBody body={post?.body} />  </Fragment> )) You get: No extra DOM wrapper Proper keys on list items Clean, valid JSX Small detail. Big difference in correctness. Save this for the next time you're mapping over data with multi-element rows. #React #JavaScript #Frontend #WebDev #ReactJS

  • text

Does the actual Fragment/ <React.Fragment> accept props?

Like
Reply

nice, didn't knew about this one, thanks mate

Like
Reply

You need key for virual DOM differing, so React know what data needs to update.

See more comments

To view or add a comment, sign in

Explore content categories