Skip to content

TodayILearned - 2023-06-21

Posted on:June 21, 2023 at 10:51 AM

#TIL - React Docs Continued

Fragments

Component functions need to return one object. I usually use a <section> tag, but technically you can also wrap the child elements with <>...</> which I recently learned is called a fragment.

When you map over an array of data, React gives you a warning regarding assigning a unique key to each mapped unit, such as the id that was assigned to this particular object or data. If your map function is returning a <>...</> object, however, you cannot pass a key so you need to use another element tag or use the more explicit syntax. I didn’t know this existed!

<Fragment key={id}>
  //....
</Fragment>

Fragments disappear from the DOM so you will not see in when you inspect via developer tools.

Why do we need to pass keys anyway?

Coding PUSH: Next time when I render list items, try to intentionally create ids (also see below).

Passing keys as props

Key does not work as a prop

Pure functions