tiennl
tiennl

Reputation: 334

Chakra UI: Change option text color and option background in Select

I have a select dropdown using ChakraUI, it like:

<Select color={"white"} bg={"black"}>
    <option value="option1">Option1</option>
    <option value="option2">Option2</option>
</Select>

When I click to dropdown, the option has both textColor and bgColor is white. I want to change option appear that textColor is black and bgColor is white. I have set color, bgColor in option field but it not working

Upvotes: 9

Views: 14722

Answers (3)

Muhammad Naveed
Muhammad Naveed

Reputation: 1

You may also style on component level for your colour theme like as below:

// components/select.ts

import { selectAnatomy } from '@chakra-ui/anatomy'
import { createMultiStyleConfigHelpers } from '@chakra-ui/react'

const { definePartsStyle, defineMultiStyleConfig } =
  createMultiStyleConfigHelpers(selectAnatomy.keys)

const baseStyle = definePartsStyle({
  // define the part you're going to style
  field: {
    background: 'secondary',
    border: 'secondary',
    '> option': {
      background: 'primary',
      color: 'white',
    },
  },
  icon: {
    color: 'primary',
  },

})

// styles/theme.ts

import { extendTheme } from "@chakra-ui/react";
import { selectComponent } from "@/components/elements/select";

export const customTheme = extendTheme({
  semanticTokens: {
    colors:{
        primary: "#212427",
        secondary: "#DEE1E5",
        highlight: "#455468",
    }
  },
  components: {
    Select: selectComponent,
  }
});

/* pages/_app.tsx */

import { ChakraProvider } from '@chakra-ui/react';
import { customTheme } from '../styles/theme';

export default function App ({ Component, pageProps }) {
  return (
      <ChakraProvider resetCSS theme={customTheme}>
        <Component {...pageProps} />   
      </ChakraProvider>
  );
}

Upvotes: 0

Zoedia
Zoedia

Reputation: 465

Intended for those who have trouble with chakra-ui's select on Window's Chrome. Here is the simplest solution I come up with.

<Select
  ...
  bg='black'
  color: 'white'
  sx={{
    '> option': {
      background: 'black',
      color: 'white',
    },
  }}
>

Note: Only background and color can be edited for select's options. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/option#styling_with_css

Upvotes: 6

tromgy
tromgy

Reputation: 5823

You will need to style the <option>s:

<Select bg="black" color="white">
  <option style={{ color: 'black' }} value="option1">
    Option1
  </option>
  <option style={{ color: 'black' }} value="option2">
    Option2
  </option>
</Select>;

Note that if you add a placeholder to <Select>, it will still be white on white when opened.

Another curious thing is that this problem does not happen in Safari, there the dropdown looks just like a standard OS menu.

Upvotes: 9

Related Questions