Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add properties to the <> empty element in React?

Tags:

reactjs

can someone explain the <> in React, it is a div or what, I see that is different basically on design, can I add a property to it, for example, if you are iterating it and want to add the required index, how can I do that?

Something like this?:

todos.map((t, i), => <key={i}>{t.name}</>)
like image 862
nevoni3008 Avatar asked Sep 12 '25 04:09

nevoni3008


2 Answers

they are Fragments: you can use <React.Fragment key={item.id}> instead of <>

function Glossary(props) {
  return (
    <div>
      {props.items.map(item => (
        // Without the `key`, React will fire a key warning
        <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </div>
  );
}

like image 183
Arash Ghazi Avatar answered Sep 14 '25 20:09

Arash Ghazi


The doc describes it quite well:

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

Source

The Idea of the fragment element is not to receive any properties. If you want to apply properties you are better of with a div, span, or some other native component.

In your case, I would go with a div and pass the key directly to it. ->

todos.map((todo) => <div key={todo.name}>{todo.name}</div>)

FYI: have accessibility in mind when choosing the right component.

like image 27
Eddie Avatar answered Sep 14 '25 20:09

Eddie