Search code examples
reactjsreact-bootstrap-typeahead

React Bootstrap Typeahead children onclick


I have been using a Premade React-Bootstrap Typeahead search-bar found here

I am having trouble accessing the child elements from the dropdown. I want to be able to have an Onclick function for the dropdown items, but it doesn't seem like I have access to the children.

Below is the code I have currently, where I use typeahead

<div className="search-bar">
  <Typeahead
    id="sample"
    options= {cities.map((city) => (city))}
    labelKey="name"
    placeholder="Enter a city"
  />
</div>

How do I get an onclick for these element cities listed?


Solution

  • You can customize menu rendering and behavior by using the renderMenu prop:

    <Typeahead
      options={options}
      renderMenu={(results, menuProps) => (
        <Menu {...menuProps}>
          {results.map((result, index) => (
            <MenuItem
              onClick={() => console.log('click!')}
              option={result}
              position={index}>
              {result.label}
            </MenuItem>
          ))}
        </Menu>
      )}
    />
    

    With the menu items exposed, you're free to add your own onClick handler to each item. Here's a working example.