简体   繁体   中英

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. eg

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/

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

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>
    )
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM