user1381745
user1381745

Reputation: 3900

Component in JSX not loading?

I'm having some issues with React not displaying data relating to a component's props:

import React from 'react';

import {ItemListing} from './ItemListing.js';

export var SearchResults = React.createClass({
    render: function() {
        console.log('Render called! SearchResults props', this.props); // Fires and displays data as expected
        return (
            <div>
                {this.props.items.forEach(function(item) {
                    console.log(item); // Fires correctly
                    <ItemListing item={item} /> // Does not run - a console.log() inside the render method of this component does not fire
                })}
            </div>
        )
    }
});

This component is loaded inside its parent as <SearchResults items={this.state.items} />, and the console.log() inside the render function above does show the props being loaded as expected (after initially loading as empty, as the data comes from an Ajax call further upstream).

However, the component inside the forEach loop doesn't appear to load, there's no display and a console.log() at the top of its render method doesn't seem to fire.

I'm very new to react so may be missing something obvious, but can anyone tell me what I'm doing wrong?

Upvotes: 1

Views: 660

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

Rather than using forEach you need to use map.

The forEach method is designed to have side-effects and therefore doesn't return a value (or rather it returns undefined). Take a look at the JSX literal after the forEach is evaluated.

return (
  <div>
    {undefined}
  </div>
)

Instead, use map and return the child components.

return (
  <div>
    {this.props.items.map(function(item) {
      console.log(item); // Fires correctly
      return <ItemListing item={item} />;
    })}
  </div>
)

After evaluation, the JSX literal would look something like this (depending on how many items in this.props.items):

return (
  <div>
    {[
      <ItemListing item={this.props.items[0]} />,
      <ItemListing item={this.props.items[1]} />,
      // ...
      <ItemListing item={this.props.items[n]} />,
    ]}
  </div>
)

Upvotes: 6

Related Questions