stukennedy
stukennedy

Reputation: 1108

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.

Upvotes: 12

Views: 3065

Answers (3)

Or Duan
Or Duan

Reputation: 13810

React 16.2 added support for Fragments, you can use it like this:

return (
  <dl>
    {_.map(array, (item) => {
      return (
        <Fragment>
          <dt>{item.def}</dt>
          <dd>{item.term}</dd>
        </Fragment>
      )
    })}
  </dl>
)

You can also use Fragment with empty tag like this:

return (
  <dl>
    {_.map(array, (item) => {
      return (
        <>
          <dt>{item.def}</dt>
          <dd>{item.term}</dd>
        </>
      )
    })}
  </dl>
)

But keep in mind that if you want to use the key attribute on Fragment tag you have to use the full version of it. More info on this react's blog

Upvotes: 10

Rifat
Rifat

Reputation: 7728

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/

Upvotes: 14

stukennedy
stukennedy

Reputation: 1108

I found the simplest way to achieve this is to map over the object keys (lodash supports this) for each item of the array and conditionally render each type of element.

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 _.map(item, (elem, key) => {
            if (key === 'def') {
              return <dt>{elem}</dt>
            } else if (key === 'term') {
              return <dd>{elem}</dd>
            }
          })
        })}
      </dl>
    )
  }
}

Upvotes: 0

Related Questions