Search code examples
csssassfluent-uifluentui-react

Is it possible to change backgroundColor of selectedItem on hover in Fluent UI?


I have a dropdown component from Fluent UI. There is a default style for selected item. I can change this style, but I couldn't change color and backgroundColor of selected item when I hover on it. Is it possible to give a custom style when I hover on selected item?

https://developer.microsoft.com/en-us/fluentui#/controls/web/dropdown

enter image description here


Solution

  • Here is a sample.

    import * as React from "react";
    import { IStackTokens, Stack } from "@fluentui/react/lib/Stack";
    import {
      Dropdown,
      DropdownMenuItemType,
      IDropdownStyles,
      IDropdownOption
    } from "@fluentui/react/lib/Dropdown";
    
    const dropdownStyles: Partial<IDropdownStyles> = {
      dropdown: { width: 300 },
      dropdownItemSelected: {
        selectors: {
          "&:before": {
            content: '""',
            position: "absolute",
            left: 0,
            top: 0,
            bottom: 0,
            width: "4px",
            background: "rgb(0, 120, 212)"
          }
        },
        "&:hover:focus": {
          backgroundColor: "blue",
          color: "white"
        }
      }
    };
    
    const options: IDropdownOption[] = [
      {
        key: "fruitsHeader",
        text: "Fruits",
        itemType: DropdownMenuItemType.Header
      },
      { key: "apple", text: "Apple" },
      { key: "banana", text: "Banana" },
      { key: "orange", text: "Orange", disabled: true },
      { key: "grape", text: "Grape" },
      { key: "divider_1", text: "-", itemType: DropdownMenuItemType.Divider },
      {
        key: "vegetablesHeader",
        text: "Vegetables",
        itemType: DropdownMenuItemType.Header
      },
      { key: "broccoli", text: "Broccoli" },
      { key: "carrot", text: "Carrot" },
      { key: "lettuce", text: "Lettuce" }
    ];
    
    const stackTokens: IStackTokens = { childrenGap: 20 };
    
    export const DropdownSelectStyleExample: React.FunctionComponent = () => {
      return (
        <Stack tokens={stackTokens}>
          <Dropdown
            placeholder="Select an option"
            label="Favorite Fruit"
            options={options}
            styles={dropdownStyles}
          />
        </Stack>
      );
    };