Ad

Returning Paired Elements In React JSX

- 1 answer

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.

Ad

Answer

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/

Ad
source: stackoverflow.com
Ad