Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Array.map to render two React elements without using React Fragments

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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!

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading