I want to design a unique CSS element with the following characteristics:
- Include a button.
- When the button is clicked, a list of items (like a dropdown list) should appear.
- We should be able to select items by clicking on them, and the parent component should be notified accordingly.
- The list should close when we click outside of it (e.g., clicking on the button again).
I tried creating a normal dropdown list using Fluent UI's Dropdown (one version and another preview version), as shown in this codesandbox. However, it doesn't meet the 4th condition specified above: selecting an item automatically closes the dropdown, whereas I wanted the list to remain open until I click outside of it.
This behavior can be seen in the default controlled multi-select Dropdown explained in this example, where the dropdown closes only when clicking outside of it. Hence, my requirement is not unreasonable.
If anyone knows how to achieve this functionality through CSS elements, possibly by modifying existing controls like Dropdown, Select, or Combobox from libraries such as Fabric UI, Fluent UI, or Material UI, your input would be greatly appreciated.
import React from "react";
import { Dropdown } from "@fluentui/react/lib/Dropdown";
import { initializeIcons } from "@fluentui/react/lib/Icons";
initializeIcons();
const numberOptions = [8, 9, 10].map((i) => ({
key: i,
text: "Number: " + i.toString()
}));
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { number: 8 };
}
onnumberChange = (_ev, option) => {
if (typeof option.key === "number") {
this.setState({ number: option.key });
}
};
render() {
return (
<div>
{`Number: ${this.state.number}`}
<br />
<br />
<Dropdown
options={numberOptions}
defaultSelectedKey={this.state.number}
onChange={this.onnumberChange}
/>
</div>
);
}
}