Search code examples
javascriptreactjsreact-bootstrap

Loop through the array and return a `Dropdown.Item` element for each item


I am trying to loop through the todos array using the JavaScript map() function. I want to return a Dropdown.Item element for each item. When I click the Dropdown.Toggle , an empty list expands. Dropdown.Item and Dropdown.Toggle are react bootstrap components.

Code here: https://stackblitz.com/edit/react-egxxcl

class App extends Component {
  constructor() {
    super();
    this.state = {
      todos: [{name: 'A', value: 10}, {name: 'B', value:20}]
    };
  }

  render() {
    return (
      <div>
       <Dropdown>
        <Dropdown.Toggle variant="success" id="dropdown-basic">
          Change
        </Dropdown.Toggle>

        <Dropdown.Menu >
          {this.state.todos.map((todo, index) => {
            <Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
          })}
        </Dropdown.Menu>
      </Dropdown>
      </div>
    );
  }
}

Solution

  • You just missed to return from map function.

    {this.state.todos.map((todo, index) => {
         return <Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
    })}
    

    or shorten,

    {this.state.todos.map((todo, index) => (
       <Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
    ))}
    

    or even shorten,

    {this.state.todos.map((todo, index) => <Dropdown.Item value={todo.value}>{todo.name}</Dropdown.Item>
    )}