AndreKR
AndreKR

Reputation: 33697

How to model a list in React

I want to render this HTML:

<div className="panel panel-default">
  <div className="panel-body">
    <dl className="dl-horizontal">
      <dt>Step 1</dt>
      <dd>
        <samp>Output 2</samp><br>
        <samp>Output 2</samp>
      </dd>
      <dt>Step 1</dt>
      <dd>
        <samp>Output 2</samp><br>
        <samp>Output 2</samp>
      </dd>
    </dl>
  </div>
</div>

The trivial way to model this in React would be:

var ResultBoxPanel = React.createClass({
  render: function () {
    return (
      <div className="panel panel-default">
        <div className="panel-body">
          <dl className="dl-horizontal">
            <ResultBoxStep name="Step 1" />
            <ResultBoxStep name="Step 2" />
          </dl>
        </div>
      </div>
    );
  }
});

var ResultBoxStep = React.createClass({
  render: function () {
    return (
      <dt>{this.props.name}</dt>
      <dd>
        <samp>Output 1</samp><br />
        <samp>Output 2</samp>
      </dd>
    );
  }
});

This doesn't work because apparently I cannot return multiple siblings from a render function.

So, how would I go about modeling this?

Upvotes: 1

Views: 1662

Answers (1)

Henrik Andersson
Henrik Andersson

Reputation: 47202

According to spec, using a span within the dl tree is not allowed but according to React it most certainly is.

However in order to keep to HTML spec this would be how you should model it.

<ResultBoxDT title={"Step 1"}/>
<ResultBoxDD name='Step 1 dd'/>
<ResultBoxDT title="Step 2" />
<ResultBoxDD name='Step 2 dd'/> 

And to make this a bit more dynamic this would be how you'd generate multiple sections, which, should also lead you to understand that you don't need to extract each tag to its own component.

{
    list.map(function(item) {
        var title = 'Step ' + item;
        var name = 'Step ' + item + ' dd';
        return [
            <ResultBoxDT title={title}/>,
            <ResultBoxDD name={name} />
        ]
    })
} 

Upvotes: 1

Related Questions