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

react- Assign jsx elements in sequence with input from array elements

I am trying to assign jsx elements sequentially in a component. this sequence should be based off of array elements of an input. let me elaborate on what i mean.

`let input = ['apple', 'ball', 'cat']`

Above is the input array and the sequence of how i want my jsx elements, jsx elements are below

```
let apple = (<div>Apple as first element</div>)
let ball = (<div>Ball as second element</div>)
let cat = (<div>Cat as third element</div>)

return (
    <>
      {input[0]}
      {input[1]}
      {input[2]}
   </>
)```

`

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

If i do the following shown above, jsx elements doesnot gets diplayed but if i do below code, jsx elements show fine.

```return (
    <>
      {apple}
      {ball}
      {cat}
   </>
)```

can someone let me know how to get the first scenario working.

>Solution :

const elements = {
  apple: <div>Apple as first element</div>,
  ball: <div>Ball as second element</div>,
  cat: <div>Cat as third element</div>
}

return (
  <>
    {input.map(val => elements[val])}
  </>
)

Or:

return (
  <>
    {input.map(val => {
      if (val === 'apple') {
        return <div>Apple as first element</div>
      } else if (val === 'ball') {
        return <div>Ball as second element</div>
      } else if (val === 'cat') {
        return <div>Cat as third element</div>
      }
    })}
  </>
)
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