Make sure to have the list available while choosing an item

I want to design a unique CSS element with the following characteristics:

  1. Include a button.
  2. When the button is clicked, a list of items (like a dropdown list) should appear.
  3. We should be able to select items by clicking on them, and the parent component should be notified accordingly.
  4. 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>
    );
  }
}

Answer №1

To solve this issue, you can utilize the `open`, `onOpenChange`, and `onOpenSelect` functionalities available in the upcoming Dropdown version.

Check out the CodeSandbox example here: https://codesandbox.io/s/inspiring-almeida-3lgtcy?file=/src/App.js

import React from "react";
import { Dropdown, Option } from "@fluentui/react-components/unstable";
import { FluentProvider, webLightTheme } from "@fluentui/react-components";
import { initializeIcons } from "@fluentui/react/lib/Icons";

initializeIcons();

const numberOptions = ["8", "9", "10"];

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { number: "9", op: false };
  }

  render() {
    return (
      <FluentProvider theme={webLightTheme}>
        <div>
          {`Number: ${this.state.number}`}
          <br />
          <br />
          <Dropdown
            open={this.state.op}
            onOpenChange={(e, data) =>
              this.setState(
                { op: data.open },
                console.log("onOpenChange", this.state.op ? "closed" : "open")
              )
            }
            onOptionSelect={(e, data) =>
              this.setState({ op: true, number: data.optionText })
            }
            defaultSelectedOptions={["9"]}
          >
            {numberOptions.map((option) => (
              <Option key={option}>{option}</Option>
            ))}
          </Dropdown>
        </div>
      </FluentProvider>
    );
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting Material UI component properties based on props

Below is my React JS code using MUI's TextField. I want to implement the error and helperText properties only when the error prop has a value. By default, the error prop is set to null. import React from 'react' import { TextField } from &ap ...

Modifying tags or categories of a post using a sidebar plugin in WordPress Gutenberg

I am currently working on integrating the functionality to add or delete a post's tag or category using a WordPress Gutenberg sidebar plugin built with React and JavaScript. Despite the lack of detailed resources on how to implement this particular us ...

Using Bootstrap 4, you can create nested rows that will automatically expand to fill their parent container, which in turn has been set

In my current setup, I have a div with the class "d-flex flex-column" that contains a navbar and a container. Within this container, there is another div with the class "d-flex flex-column" which then contains two rows. I am using flex-grow to make the con ...

Directly uploading files to AWS using React/NextJS is a seamless process

After going through some tutorials, I have successfully created code for uploading files to AWS. However, the typical workflow involves: User chooses a file from their device File is uploaded to our server File is then sent to AWS I am looking to by-pass ...

Ways to integrate a React app into an HTML file without using npm start or other similar commands

Hey there! I'm diving into the world of ReactJS and wondering if it's possible to make my react app run directly from the .html file in a browser without needing to call a server. Of course, having a server for other functionalities is fine, but ...

Passing "this" to the context provider value in React

While experimenting with the useContext in a class component, I decided to create a basic React (Next.js) application. The app consists of a single button that invokes a function in the context to update the state and trigger a re-render of the home compon ...

A compatibility issue between jQuery and Internet Explorer 7

, you can find the following code: $("body").delegate('area[id=area_kontakt]','mouseover mouseleave', function(e){ if (e.type == 'mouseover') { $("#kontakt_tip").css('display','block'); } else { $( ...

When a <dl> element is nested within an <ol>, it will be rendered as a list format

I'm facing an issue with my CSS that affects how different browsers render definition lists embedded within ordered lists. In IE10, the list displays as expected - a bulleted list inside the ordered list without affecting the numbering. However, Firef ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Enabling sidebar functionality for every component in React JS using React Router v6

I am currently using react router dom v6 and encountering an issue where the sidebar disappears whenever I click on any component in the app. I need to find a way to keep the sidebar visible across all components. Sidebar Available Sidebar Gone Index.js ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

Implementing image caching in tvOS with React-Native: A step-by-step guide

Looking to Implement Image Caching in tvOS using React Native I'm trying to figure out how to cache images that I download from the internet on my Apple TV. I've experimented with various libraries, but none seem to be compatible with tvOS. Any ...

What is the easiest method to design an email subscription form that remains fixed on the top right corner of the screen?

Looking for advice on setting up a sleek email signup bar that remains at the top of the browser while users scroll and navigate through different pages. I am working with WordPress and have jquery already loaded, but have not yet worked with either. Up ...

Troubleshooting NextJS useEffect with localStorage

I am attempting to retrieve a string from local storage, perform a check against it, and redirect the page based on the value stored in local storage. However, I am facing an issue where the page is briefly visible before redirecting to the original page. ...

When executing npm run dev, the Next/image component encounters an error stating that the "width" property is missing and required

When I start my Next.js app with npm run dev, the Image component triggers an error stating that the "width" property is missing. In order to resolve this issue and get the app running properly, I had to define both width and height as inline attributes f ...

extract { CODE } from '@env'

In the process of developing an app using React Js, I encountered a challenge with hiding an API key. To address this issue, I created a ".env" file at the project's root to securely store the key. However, when attempting to import it into App.js, I ...

What is the formula for determining the grid width when an item exceeds the column size?

I am working with a grid that matches the size of an image, which can be adjusted to be both smaller and larger in size. Within this grid, I have 6 items. Each item is wider than the columns in the grid. In order to achieve the desired width for the gri ...

Is there a way to set an image as the background of my HTML screen?

{% extends "layout.html" %} {% block app_content %} <div> {% from "_formhelpers.html" import render_field %} <form method="post" enctype="multipart/form-data"> <div class = "container"> < ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

One cannot focus on HTML if it's disabled

I am currently exploring options to prevent an input from receiving focus without disabling it entirely. I need the backend to still retrieve data, but I want to restrict user editing of the input fields at certain times. Disabling the input is not an opti ...