Home > Software design >  How to use Array.map to render two React elements without using React Fragments
How to use Array.map to render two React elements without using React Fragments

Time:11-10

Here's the piece of code I'm trying to build programmatically:

<RadioGroup>

  <Radio key={1}/>
  <div>Unique Content 1</div>

  <Radio key={2}/>
  <div>Unique Content 2</div>

  <Radio key={3}/>
  <div>Unique Content 3</div>

  <Radio key={4}/>
  <div>Unique Content 4</div>

</RadioGroup>

Typically, you'd write the code this way:

const arr = [1, 2, 3, 4];

<RadioGroup>
  {arr.map(a => (
    <>
      <Radio key={a}/>
      <div>Unique Content {a}</div>
    </>
  ))}
</RadioGroup>

But due to specific constraints, I cannot use React Fragments (<> </>) to wrap the Radio and div elements together. Because it would end up looking like this:

<RadioGroup>
    
  <>
    <Radio key={1}/>
    <div>Unique Content 1</div>
  </>

  <>
    <Radio key={2}/>
    <div>Unique Content 2</div>
  </>

  <>
    <Radio key={3}/>
    <div>Unique Content 3</div>
  </>

  <>
    <Radio key={4}/>
    <div>Unique Content 4</div>
  </>

</RadioGroup>

I am aware that these fragment elements do not translate to real DOM nodes, but I need the Radio components to the be the first level children under RadioGroup along with the div. And I understand that returning more than one JSX element from a function is a violation.

Is there any way I can achieve this with or without using Array.map()? Thanks in advance!

CodePudding user response:

One option is to return an array with those two elements from the callback, then flatten the array of arrays..

<RadioGroup>
  {arr.map(a => [
    <Radio key={a}/>,
    <div>Unique Content {a}</div>
  ]).flat()}
</RadioGroup>
  • Related