Home > Blockchain >  How to add entries to dropdown during runtime?
How to add entries to dropdown during runtime?

Time:11-08

I am attempting to create a dropdown that displays the name of the currently selected item, where the amount of items are pulled from a json file that is stored locally. I found this post: link, however this is in reference to the form component, and it also seems to be outdated in reference to how to use the current version of react-bootstrap.

I tried constructing a string and injecting the string, but that obviously doesn't work. I couldn't find any information on dynamically creating a number of dropdown elements on the docs.

import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown';

import SponsorManager from './SponsorManager';
const sponsorManager = new SponsorManager();

function App() {
  var sponsorIds = sponsorManager.getSponsors();
  var dropdowns = ""
  for (const [key, value] of Object.entries(sponsorIds)) {
    var dropdowntemplate = `<Dropdown.Item href="#/action-1">${value.displayName}</Dropdown.Item>\n`
    dropdowns  = dropdowntemplate;
  }

 return (
    <React.Fragment>
      <div>
        <DropdownButton id="dropdown-basic-button" title="Dropdown button">
          {dropdowns}
        </DropdownButton>
      </div>
    </React.Fragment>
  );
}

CodePudding user response:

I found that there was actually an answer that seemed to work for me from that link. Using that, I came up with this solution that I really like and is encapsulated:

import React from 'react';
import DropdownButton from 'react-bootstrap/DropdownButton';
import Dropdown from 'react-bootstrap/Dropdown';

class DynamicDropdown extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            selected: this.props.items[0].displayName,
            items: this.props.items
        };
    }

    changeSelected(selected) {
        this.setState({ selected: selected });
    }

    render() {
        let itemDisplays = this.state.items.map(v => (
            <Dropdown.Item as="button" key={v.id} value={v.id} ><div onClick={(e) => this.changeSelected(e.target.innerText)}>{v.displayName}</div></Dropdown.Item>
        ));

        return (
            <div>
                <DropdownButton id="dropdown-basic-button" title={this.state.selected}>
                    {itemDisplays}
                </DropdownButton>
            </div>
        );
    }
}
export default DynamicDropdown;
  • Related