Blankman
Blankman

Reputation: 267390

How do render a dropdownl list with options coming from state

I want to display a dynamic drop down list but I am a little confused on how to do it.

I want to iterate through my users like:

users.map((user) => {
}

Do I have to create another function to do this or can I do it all in a single function?

_renderDropdown() {
   const { users } = this.props;

   return (
      <select name="userDdl" onChange={::this._onSelectedUserChange}>
      </select>
   );

}

_onSelectedUserChange(e) {
   console.log('user selected change called...');
}

Upvotes: 0

Views: 42

Answers (3)

Faizuddin Mohammed
Faizuddin Mohammed

Reputation: 4328

You can do something like:

<select name="userDdl" onChange={::this._onSelectedUserChange}>
 {users.map(user => (
  <option key={user.id} value={user.id}>{user.name}</option>
 ))}
</select>

Upvotes: 1

Colin Ricardo
Colin Ricardo

Reputation: 17269

Here's a minimal example:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    users: ["Elon", "Steve", "Bill"]
  };

  renderOptions() {
    return this.state.users.map(u => {
      return <option value={u}>{u}</option>;
    });
  }

  render() {
    return <select options>{this.renderOptions()}</select>;
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

CodeSandbox here.

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

It's your choice where you would like to place the logic. To render the options based on the users, you can do like this:

{
 users.map((user, index) => {
  return (
    <option key={index}>{user.value}</option>
  )
 })
}

Upvotes: 0

Related Questions