nevoni3008
nevoni3008

Reputation: 457

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

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}</>)

Upvotes: 24

Views: 8159

Answers (3)

Arash Ghazi
Arash Ghazi

Reputation: 1001

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>
  );
}

Upvotes: 40

Parham Abolghasemi
Parham Abolghasemi

Reputation: 148

you can simply use React.Fragment

Tip: it's not a good idea to use index as key.

todos.map((item, index) => (
  <React.Fragment key={index}>
    <p>{item.title}</p>
  </React.Fragment>
)); 

Upvotes: 0

Eddie
Eddie

Reputation: 39

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.

Upvotes: 1

Related Questions