#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
<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?
- Basically, to keep order.
- Keys tell React which component corresponds to which array item.
- There is a possibility that array items move, get inserted, or deleted, so we need to have unique keys.
- 💡 Up until now, if I needed to arbitrarily pass something to the ‘key’, I simply used the index of the item that belongs in the array. Now, looking through the docs, I realize this isn’t great practice since the order of the array can shift around.
Coding PUSH: Next time when I render list items, try to intentionally create ids (also see below).
Passing keys as props
- What if the data doesn’t have a key from its source? The React.dev docs recommends using
crypto.randomUUID()
or a package such asuuid
. - If you are using data from a database they usually have id keys already.
- NOTE: Do not change keys - don’t generate while rendering (e.g. do NOT pass
key={Math.random()}
-> this will result in different key numbers each render).
Key does not work as a prop
- If you want to use the id value during Component rendering, unfortunately you cannot utilize ‘key’ as a prop even though it seems like you’re passing it down. This means you need to additionally send a
id
prop to the component.
Pure functions
- only perform a calculation
- doesn’t change any objects or variables that existed before it was called
- same input -> same output
- Components also have to be this way - same ingredients -> same result because same recipe.