1

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>
    );
  }
}
Umbro
  • 1,984
  • 12
  • 40
  • 99

2 Answers2

2

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>
)}
ravibagul91
  • 20,072
  • 5
  • 36
  • 59
1

You don't return anything from the map function, you can wrap it in parentheses or without to avoid using the return keyword, also don't forget the key prop.

I highly recommend using a linter to help you catch those small errors

You can also destructure value and name from the map callback function using ({})

({ propName })

<Dropdown.Menu>
  {this.state.todos.map(({ name, value }) => (
    <Dropdown.Item key={name} value={value}>{name}</Dropdown.Item>
  ))}
</Dropdown.Menu>
Asaf Aviv
  • 11,279
  • 1
  • 28
  • 45
  • And does `linter` help you catch variables that are declared and not used? – Umbro Aug 03 '19 at 01:46
  • @Umbro Yes there are tons of "rules" that you can define to make your code consistent and you can combine it with a code formatter to auto format your code on save – Asaf Aviv Aug 03 '19 at 01:47