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

Display a json array of object in ReactJS

I have an array of object and want display in a single line in ReactJS. The object look like:

[
  {
     name:"jane",
     age : "20"
  },
  {
     name:"mary",
     age : "21"
  }
  {
     name:"john",
     age : "19"
  }
]

I want display the result to be :

jane 20, mary 21, john 19

e.g

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

<span className="name>data.name</span> <span className="age>data.age</span>

I have a function but that concat the value but not sure now to get my desire output

const getData = () => {
    var val = ''
    roles.map((data, inx) => {
      val = val + data.name + data.age

    })
    return (
      <span>{val}</span>
    )
  }

how can I do this

>Solution :

Concatenating like

val = val + data.name + data.age

won’t work, because you want JSX elements (spans), not plain strings.

When mapping, check the index. If the index is 1 or more, add a comma before the first span when creating the JSX.

const arr = [
  {
     name:"jane",
     age : "20"
  },
  {
     name:"mary",
     age : "21"
  },
  {
     name:"john",
     age : "19"
  }
]
const App = () => {
    return arr.map(({ name, age }, i) => (
        <React.Fragment>
            {i === 0 ? null : ','}
            <span className="name">{name}</span> <span className="age">{age}</span>
        </React.Fragment>
    ));
};

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></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