0

So usually it's obvious to me how to use the key property.

const test = [1,2,3,4,5];
return (
    <>
        {test.map(x => <div key={x.toString()}>{x}</div>)}
    </>
);

But how is the correct way to do it if my map function looks like this:

const mapNumbers = (x: number) => (
<>
  <div>{x}</div>
  <div>{x+2}</div>
</>
)

Since I'm now mapping to two divs I'm not sure how to handle the key property here.

Tobias Kiehnlein
  • 184
  • 3
  • 12

1 Answers1

0

Assuming you're mapping a list of unique numbers, you can wrap everything into a container React.Fragment (details).

const mapNumbers = (x: number) => (
    <React.Fragment key={x}> 
        <div>{x}</div>
        <div>{x + 2}</div>
    </React.Fragment>
)

Edit: With React.Fragment as suggested by @marzelin.