0

I am trying to build a dropdown-menu and add data from my array to the dropdown-item. My current code isn't returning anything into my const Users. How can I use the array to add data into the dropdown-item?

UserDisplay component

   const UserDisplay = ({ users }) => {
      const Users = users.map(user => {
        let i = 0;
        <a className="dropdown-item" href="#">
          {user[i]}
        </a>;
        i++;
      });
      return (
        <div className="dropdown-menu" id="users">
          <a className="dropdown-item" href="#">
            Online Users
          </a>
          <div className="dropdown-divider" />
             {Users}
        </div>
      );
    };

Parent Component ChatLayout

return (
      <div className="chat navbar fixed-bottom">
        <div className="btn-group dropup">
          <button
            type="button"
            className="btn btn-secondary dropdown-toggle"
            data-toggle="dropdown"
            aria-haspopup="true"
            aria-expanded="false"
          >
            Chat
          </button>
          <UserDisplay users={[this.state.users]} />
        </div>
        <ul id="messages">
          <div />
        </ul>
        <form onSubmit={this.onSubmit}>
          <textarea
            name="message"
            placeholder="Enter your message here"
            autoComplete="off"
            type="submit"
            onKeyDown={this.onEnterPress}
            value={this.state.message}
            onChange={this.onChange}
          />
          <input type="submit" className="btn btn-info btn-block mt-4" />
        </form>
      </div>
    );
Snoopy
  • 1,257
  • 2
  • 19
  • 32

2 Answers2

0

You don't need to define and iterate i.. the .map already keeps track of the array index. Assuming users has data it should work like this...

  UserDisplay(users) {
      const Users = users.map((user,i) => {
        return (
            <a className="dropdown-item" key={i} href="#">
              {user}
            </a>)
      });
      return (
        <div className="dropdown-menu" id="users">
          <a className="dropdown-item" href="#">
            Online Users
          </a>
          <div className="dropdown-divider" />
          {Users}
        </div>
      );
  };

Working Codeply: https://www.codeply.com/go/DnqpGhozra

Carol Skelly
  • 351,302
  • 90
  • 710
  • 624
0

You are destructing props object and get users out of it so its fine. basically map returns a list of array so you dont have return anything.

You need to iterate to the first element of users like

const Users = users[0].map((user,i) => {
        console.log(user);
        return (
            <a className="dropdown-item" key={i} href="#">
              {user}
            </a>)
      });

OR just pass users directly

 <UserDisplay users={this.state.users} />
Atul
  • 420
  • 2
  • 10