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
<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
CodePudding user response:
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>