Skip to content Skip to sidebar Skip to footer

Rendering Reactjs Component Based On A List Of Objects

I have the following component: articles_list.jsx import React from 'react'; import './articles_list.css'; export default class ArticlesList extends React.Component { construct

Solution 1:

return statement inside a forEach doesn't return the value instead it acts like a continue statement, you need to make use of map

varteste = () => {
  if (this.state.articles === null) {
    return(<div>No articles</div>)
  } else {
      {this.state.articles.map( function(element, index) {
        console.log(element);
        return<divkey={index}>{element.title}</div>;
      })}
  }
}

else if you want to go with forEach you need to modify your code like

render() {

    var teste = []

      if (this.state.articles === null) {
        teste.push(<div>No articles</div>)
      } else {
          {this.state.articles.forEach( function(element, index) {
            console.log(element);
            teste.push( <divkey={index}>{element.title}</div>);
          })}
      }
    }

    return(
      <divclassName="articles_list"><divclassName="articles_list_title">
          ARTICLES
        </div><div>{teste}</div></div>
    );
  }

Solution 2:

You may try something like this.

import _ from'lodash';
renderArticles() {
  return _.map(this.state.articles, article => {
    return (
      <liclassName="list-group-item"key={article.id}>
          {article.title}
      </li>
    );
  });
}


  render() {
    return (
      <div><h3>Articles</h3><ulclassName="list-group">
          {this.renderArticles()}
        </ul></div>
    );
  }

Map over the list and render it one by one. Here I am using lodash map helper to get this done. Hope this helps. Happy coding.

Post a Comment for "Rendering Reactjs Component Based On A List Of Objects"