The Problem:
In React, you want to create a DOM structure by mapping an array, but each item in the array should return 2 elements. e.g.
import React from 'react'
import _ from 'lodash'
let { Component } = React
export default class DataList extends Component {
render () {
let array = [
{def: 'item1', term: 'term1', obj1: 'rand'},
{def: 'item2', term: 'term2'}
]
return (
<dl>
{_.map(array, (item) => {
return (
<dt>{item.def}</dt>
<dd>{item.term}</dd>
)
})}
</dl>
)
}
}
React doesn't let you render siblings without wrapping them in a container element, which would break the DOM structure here.
You could do something simpler with reduce
like this:
import React, { Component } from 'react';
export default class DataList extends Component {
render () {
const array = [
{def: 'item1', term: 'term1', obj1: 'rand'},
{def: 'item2', term: 'term2'}
];
return (
<dl>
{array.reduce((acc, item, idx) => {
return acc.concat([
<dt key={`def-${idx}`}>{item.def}</dt>,
<dd key={`term-${idx}`}>{item.term}</dd>
]);
}, [])}
</dl>
);
}
}
DEMO :: https://jsfiddle.net/rifat/caray95v/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With