1

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?

1 Answer 1

6

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>
)
Sign up to request clarification or add additional context in comments.

1 Comment

Raaaaage - I had been using map() previously, but left out the return keyword. It's always the simple things :( Thank you very much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.