Ad

How To Append Element To Variable To Be Render In React

- 1 answer

Given a react component like below (https://jsfiddle.net/69z2wepo/28684/):

var Hello = React.createClass({
  render: function() {
    let { cond, name } = this.props;
    let content, content2;
    if (cond){
      content = (<div>Hello { name } </div>);
      content2 = (<div>content 2</div>);
    }

    return (
      <div>
        { content }
        { content2 }
      </div>
    )
  }
});

ReactDOM.render(
  <Hello name="World" cond={ true } />,
  document.getElementById('container')
);

How can I achieve something like:

content += (<div>content 2</div>) //not working

and then render the content in a single content variable instead of both content and content 2?

Ad

Answer

var Hello = React.createClass({
  render: function() {
    let { cond, name } = this.props;
    let content, content2, contents;
    if (cond){
        content = (<div>Hello { name } </div>);
      content2 = (<div>content 2</div>);
      contents = [content, content2];
    }

    return (
        <div>
        { contents }
      </div>
    )
  }
});

ReactDOM.render(
  <Hello name="World" cond={ true } />,
  document.getElementById('container')
);

https://jsfiddle.net/69z2wepo/28687/

Ad
source: stackoverflow.com
Ad