C
C
ChrisJonson2016-04-30 00:38:47
JavaScript
ChrisJonson, 2016-04-30 00:38:47

How to output an array of strings in a React component after a condition?

The component outputs articles from a json file. Some articles are stored as a normal string, and some as an array of strings (to split into paragraphs). In rendering, a function is called in which the condition checks whether there is a regular string or an array, and depending on this, outputs differently.
If the article is a regular string, then it is displayed normally. And if it is in the form of an array of strings, then it does not want to render , although errors do not pop up and each line is displayed normally in the console log. Why is that? How to render an array after a condition?

var ArticleContent = React.createClass({
  renderContent: function(){
    if (typeof this.props.content == 'string'){
      // 1. цельная строка без абзацев спокойно рендерится  
      return <p>{this.props.content}</p> 
    } else {
      <div>
        {
             this.props.content.map(function(item, i){
             // 2. массив строк: каждая строка выводится в консоль, но не рендерится
             console.log(item);
             return <p key={i}>{item}</p>
         })
        }
         
       </div>
    }
  },
  render: function(){
    return (
      <div>
        {this.renderContent()}
      </div>
    )
  }
});

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman, 2016-04-30
@r_zaycev

Array.map returns an array

D
Dmitry Belyaev, 2016-04-30
@bingo347

the block after else does not return anything, it should be like this:

var ArticleContent = React.createClass({
  renderContent: function(){
    if (typeof this.props.content == 'string'){
      // 1. цельная строка без абзацев спокойно рендерится  
      return <p>{this.props.content}</p> 
    } else {
      return (
        <div>
        {
             this.props.content.map(function(item, i){
                // 2. массив строк: каждая строка выводится в консоль, но не рендерится
                console.log(item);
                return <p key={i}>{item}</p>
             }).join('');
        }
        </div>
      );
    }
  },
  render: function(){
    return (
      <div>
        {this.renderContent()}
      </div>
    );
  }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question