Home > OS >  What's the best practice for rendering a list component in React?
What's the best practice for rendering a list component in React?

Time:04-29

Which one is the better approach for creating a list component in react and why? I've seen both approach but I am curious if there's a best practice when it comes to this

1. A Component that contains the list container and list items

...
<List items={items} />
...
function List({items}) {
  return (
    <ul className={styles.listContainer}>
      {items.map(item =>{
        return (
          <li key={item.id}>
            {/* list item content here */}
          </li>
        )
      })}
    </ul>
  )
}

2. A Component only for the list item

...
<ul className={styles.listContainer}>
  {items.map(item => <ListItem key={item.id} item={item} /> )}
</ul>
...

CodePudding user response:

The first approach is better in my opinion

If you have a complex component in your li you can define it separately so it can be used outside a ul

like this

function List({items}) => {
  return (
    <ul>
      {items.map((item, i) => <li key={i}><OtherComponent {...item} /></li> )}
    </ul>
   )
}

PS don't forget to add a key attribute

CodePudding user response:

It depends what your lists and items are doing in addition to just being a list item.

If they are just an <li> showing some content and nothing more, then use an <li>.

If each item is interactive, needing to store state etc., then it may be appropriate to use a custom component.

Rendering a react component of any kind adds some performance overhead, however small, so a basic rule is use the built-in elements at the start, then replace them with react components when you need to.

As an aside, whichever way you go, you are rendering an array of elements, so you should add a key to the <ListItem> or <li>, e.g.

{items.map(item => <ListItem item={item} key={item.id} /> )}

  • Related