StochasticNerd StochasticNerd - 1 month ago 7
React JSX Question

List elements not rendering in React

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.

Answer

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>)}