简体   繁体   中英

Add elements to existing React DropdownButton

I am using react and react-boostrap.

I have created a Dropdown Button which on render has no Dropdown.Item elements inside. When useEffect is called, I'm trying to append results from a server into the dropdown button.

My HTML is the following:

 <Container className="mt-3"> <InputGroup> <DropdownButton as={InputGroup.Prepend} title="Existing Label" id="input-group-dropdown-1"> <Dropdown.Item></Dropdown.Item> </DropdownButton> <FormControl id="nameForm" placeholder="Name of person" /> <FormControl id="labelForm" placeholder="Label: Criminal or Citizen" /> </InputGroup> </Container>

My code to append the elements is the following:

    var dropdownItem = document.createElement("Dropdown.Item");
    dropdownItem.value = jsonArray[i];
    var splitString = jsonArray[i].split("-");
    var formNameText = splitString[0].replace(' ', '');
    var formLabelText = splitString[1].replace(' ', '');
    dropdownItem.onClick = "{changeFormText(formNameText, formLabelText)}"
    document.getElementById('input-group-dropdown-1').append(dropdownItem)

My issue is, that no elements end up inside the DropdownButton tag. I have tried using innerHTML, however it seems to overwrite the text field of the parent button.

I might be misunderstanding basic elements of react, but haven't been able to find a solution through google.

According to your comment your response is an array what you can do is to set that array to any state

If you are using functional component then do something like this

const [dropdown,setDropdown] = React.useState([]);

// Inside your useEffect  you can do something like this

useEffect(()=>{
// After your server response
setDropdown(response);
},[])

// Then your jsx will be like this

    <DropdownButton as={InputGroup.Prepend} title="Existing Label" id="input-group-dropdown-1">
      {dropdown.map((item,i)=><Dropdown.Item key={i}>{item}</Dropdown.Item>)}
    </DropdownButton>

This will only show data after your server response so i hope it helps

you could append elements based on a model in jsx .

const Component = ({items}) => {
   return (
   <Container className="mt-3">
    <InputGroup>
      <DropdownButton as={InputGroup.Prepend} title="Existing Label" id="input-group-dropdown-1">
        {
           items.map((name, index) => (<DropdownButton.Item key={index}>{name}</DropdownButton.Item>))
        }
      </DropdownButton>
      <FormControl id="nameForm" placeholder="Name of person" />
      <FormControl id="labelForm" placeholder="Label: Criminal or Citizen" />
    </InputGroup>
  </Container>
   )
}


assuming items is an array of strings you want to add to dropdown

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM