6

This is my Sidebar component.

const Sidebar = React.createClass({
  render(){
    let props = this.props;
    return(
      <div className= 'row'>
      <h2>All Rooms</h2>
        <ul>
          {props.rooms.map((room, i) => {
            <li key={i}> {room.name} </li>
          })}
        </ul>
        {props.addingRoom && <input ref='add' />}
      </div>

    );
  }
})

This is where I render it populating one room.

ReactDOM.render(<App>
  <Sidebar rooms={[ { name: 'First Room'} ]} addingRoom={true} />
  </App>, document.getElementById('root'));

The contents inside the <ul></ul> tag don't render at all. Any idea what I could be missing.

1 Answers1

17

You aren't returning anything from the map function, so it renders nothing inside the unordered list. In your arrow function, you do:

(room, i) => {
    //statements
}

This doesn't return anything. Array.prototype.map requires a callback that returns a value to do anything. map transform elements to the array, mapping (executing) the callback on each element. The return value is what the value is in the corresponding position in the returned and mapped array.

You must return the list element in the map function like so:

<ul>
    {props.rooms.map((room, i) => {
      return <li key={i}> {room.name} </li>;
    })}
</ul>

Now, the mapped array of list elements is rendered because the list element is returned.

To make this shorter, you may write it in the form (params) => value which is equivalent to the above, where value is the returned value, like so:

{props.room.map((room, i) => <li key={i}> {room.name} </li>)}
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • 1
    Why doesn't the react documentation use "return" in their example? https://reactjs.org/docs/lists-and-keys.html – mimic Feb 02 '20 at 02:57
  • 1
    @mimic Because they are using implicit return syntax (see the second code snippet in my answer). If you write `(params) => value` then `value` is implicitly returned-in the docs' case it's a JSX element. – Andrew Li Feb 02 '20 at 02:59
  • Thanks, I didn't notice there are no curly brackets and it makes the game. – mimic Feb 02 '20 at 03:11