Search code examples
javascriptreact-bootstrap

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.


Solution

  • 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