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 {

  constructor(props) {
    super(props);
    this.state = {
      articles: null
    }
  }

  componentWillMount() {
    fetch('/articles_all')
    .then(res => res.json())
    .then(json => {
      this.setState({
        articles: json.articles
      });
    });
  }

  render() {

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

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

Although the JSON request is working fine and returning an array with five JSON objects, they just don't render!

I am new to ReactJS and read (and watched) lots of tutorials, but it seems I am missing something.

Any suggestions?

Upvotes: 1

Views: 486

Answers (2)

Shubham Khatri
Shubham Khatri

Reputation: 281646

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

var teste = () => {
  if (this.state.articles === null) {
    return(<div>No articles</div>)
  } else {
      {this.state.articles.map( function(element, index) {
        console.log(element);
        return <div key={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( <div key={index}>{element.title}</div>);
          })}
      }
    }

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

Upvotes: 1

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You may try something like this.

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


  render() {
    return (
      <div>
        <h3>Articles</h3>
        <ul className="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.

Upvotes: 1

Related Questions