Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React won't render within map function

I'm trying to render an array containing some objects using the JS function map(). However when I return the text nothing is shown:

console.log(this.props.project.projects); // (2) [{…}, {…}]
  this.props.project.projects.map((item, index) => {
    console.log(item.projectDescription); //"Testproject"
    return (
        <div key={index}>
         {item.projectDescription}
        </div>
      )
  })

I just don't get it, why there is no text shown, since the console.log(item.projectDescription) shows exactly what I want to display.

Update: It works when I change it to this:

return this.props.project.projects.map((item, index) => (
        <div key={index} style={{ color: '#fff' }}>
         {item.projektBeschreibung}
        </div>
      ))

I already thought about using the foreach-method but I think it should actually work using the map()-function.

Here you can see also the render method of my Component.

class ProjectRow extends Component {

  renderProjects() {
    console.log(this.props.project);
    if (this.props.project.loading) {
    return (
      <div style={{color: '#fff'}}>
        Loading
      </div>
    )
    } else {
      console.log(this.props.project.projects);
      this.props.project.projects.map((item, index) => {
        console.log(item);
        console.log(item.projektBeschreibung);
        console.log(index);
        return (
            <div key={index}>
             {item.projektBeschreibung}
            </div>
          )
      })
    }
  }

  render() {
    return (
      <div>
        {this.renderProjects()}
      </div>
    );
  }
}
like image 567
Zander Avatar asked Jan 03 '23 00:01

Zander


1 Answers

The renderProjects function is not returning anything when it hits your else case. Here is an example of use:

renderProjects() {
  console.log(this.props.project);

  if (this.props.project.loading) {
    return (
      <div style={{color: '#fff'}}>
        Loading
      </div>
    )
  } else {
    console.log(this.props.project.projects);

    // added return statement here
    return this.props.project.projects.map((item, index) => {
      console.log(item);
      console.log(item.projektBeschreibung);
      console.log(index);
      return (
        <div key={index}>
          {item.projektBeschreibung}
        </div>
      )
    })
  }
}
like image 110
Eric Hasselbring Avatar answered Jan 05 '23 14:01

Eric Hasselbring