Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning paired elements in React JSX

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.

like image 766
stukennedy Avatar asked Mar 03 '16 10:03

stukennedy


1 Answers

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/

like image 94
Rifat Avatar answered Oct 24 '22 11:10

Rifat