Search code examples
reactjsdownshift

Downshift in Reactjs - Menu dropdown only displaying selected item


Im having trouble using Downshift, Initially I have all the menu options but once I select one option, thats the only one that shows in the menu the next time I click on it.

enter image description here

This is my current code, any feedback on whats causing that?

const dropdownItems = [
  { value: 'All' },
  { value: 'Database A' },
  { value: 'Database B' },
  { value: 'Database C' },
  { value: 'Database D' },
];
return (
  <Downshift itemToString={item => (item ? item.value : '')}>
    {({
      getMenuProps,
      getItemProps,
      getToggleButtonProps,
      getRootProps,
      isOpen,
      inputValue,
      selectedItem,
      highlightedIndex,
    }) => console.log(
      selectedItem === null ? dropdownItems[0].value : selectedItem.value,
    ) || (
        <Container {...getRootProps()}>
          <button {...getToggleButtonProps()}>
            {isOpen
              ? selectedItem === null
                ? dropdownItems[0].value
                : selectedItem.value
              : selectedItem === null
                ? dropdownItems[0].value
                : selectedItem.value}
          </button>
          {isOpen ? (
            <Menu {...getMenuProps()}>
              {dropdownItems
                .filter(
                  item => !inputValue || item.value.includes(inputValue),
                )
                .map((item, index) => (
                  <Item
                    {...getItemProps({
                      key: item.value,
                      index,
                      item,
                      style: {
                        fontWeight:
                          index === highlightedIndex
                            ? 'bold'
                            : null,
                      },
                    })}
                  >
                    {item.value}
                  </Item>
                ))}
            </Menu>
          ) : null}
        </Container>
      )
    }
  </Downshift>
);

Solution

  • .filter(item => !inputValue || item.value.includes(inputValue),) 
    

    To fix this problem, I removed the .filter, It was causing only the selected value to show in the dropdown.

    This is the updated menu tag

     <Menu {...getMenuProps()}>
         {dropdownItems.map((item, index) => (
            <Item
                {...getItemProps({
                      key: item.value,
                     index,
                       item,
                          style: {
                      fontWeight:
                       index === highlightedIndex
                        ? 'bold'
                        : null,
                           },
                            })}
                  >
              {item.value}
             </Item>
             ))}
              </Menu>