chakra-react-select

repository·main·Indexed 21 days ago

https://github.com/csandman/chakra-react-select

A Chakra UI wrapper for the react-select library, specifically optimized for Chakra UI v3. It provides a set of select components—including Select, CreatableSelect, AsyncSelect, and AsyncCreatableSelect—that integrate react-select's functionality with Chakra UI's styling system, props, and theme recipes. The package includes a crs-codemod tool for programmatic upgrades and supports TypeScript with specialized types like ChakraStylesConfig and OptionBase.

Tokens
9.9K
Snippets
30
Records
37
Agent score
73%

What's inside chakra-react-select

  1. Customize styles via Chakra Theme Recipes

    main

    Most components in chakra-react-select pull their base styles from your global Chakra theme recipes. Modifying these recipes will update all instances of the components in this package.

    Warning: Some theme styles are manually overridden by this package. If your custom theme styles are not applying correctly, use the chakraStyles prop instead, as it always takes the highest priority.

    | react-select component | chakra-ui recipe |
    |------------------------|-----------------|
    | ClearIndicator         | select.clearTrigger |
    | Control                | input |
    | DropdownIndicator      | select.indicator |
    | Group                  | select.itemGroup |
    | GroupHeading           | select.itemGroupLabel |
    | IndicatorsContainer    | select.indicatorGroup |
    | LoadingIndicator       | spinner |
    | MenuList               | select.content |
    | MultiValueContainer    | tag.root |
    | MultiValueLabel        | tag.label |
    | MultiValueRemove       | tag.endElement / tag.closeTrigger |
    | Option                 | select.item |
    | SelectContainer        | select.root |
  2. Understand the relationship between chakra-react-select and react-select

    main

    Core Concept: A Wrapper Library

    chakra-react-select is a wrapper around the react-select library, styled using Chakra UI.

    Key implications for developers:

    • API Compatibility: It accepts almost all props that the original react-select accepts. If you know how to use react-select, you already know how to use chakra-react-select.
    • Prop Inheritance: All exports and types from the original react-select package are also exported from chakra-react-select (with the exception of the root Select components).
    • Troubleshooting: Because it is a wrapper, many functional questions (how to handle values, how to filter, etc.) are actually questions about react-select. It is recommended to consult the react-select documentation for core logic behavior.
  3. Use `className` and `classNamePrefix` for CSS styling

    main

    You can style sub-components using standard CSS classes.

    • Providing className to the Select component applies it to the SelectContainer.
    • Providing classNamePrefix applies a prefix to all inner elements.

    Example with classNamePrefix="crs":

    <div class="crs__control">
      <div class="crs__value-container">...</div>
      <div class="crs__indicators">...</div>
    </div>
  4. Customize Select components using chakraComponents

    main

    You can customize the internal parts of the Select by passing a components object to the Select component. This package exports these as chakraComponents to avoid conflicts with the original react-select exports.

    Note on missing components: The following components from react-select are not included in chakraComponents due to compatibility/implementation reasons:

    • CrossIcon
    • DownChevron
    • MenuPortal (If you need to customize MenuPortal, use the original from the react-select components import).

    To replace icons like CrossIcon or DownChevron, the recommended approach is to wrap chakraComponents.ClearIndicator or chakraComponents.DropdownIndicator and pass your own icons as children.

    import {
      type GroupBase,
      type SelectComponentsConfig,
      chakraComponents,
    } from "chakra-react-select";
    import { LuArrowDown, LuCircleX } from "react-icons/lu";
    
    interface Option {
      label: string;
      value: string;
    }
    
    const components: SelectComponentsConfig<Option, true, GroupBase<Option>> = {
      ClearIndicator: (props) => (
        <chakraComponents.ClearIndicator {...props}>
          <LuCircleX />
        </chakraComponents.ClearIndicator>
      ),
      DropdownIndicator: (props) => (
        <chakraComponents.DropdownIndicator {...props}>
          <LuArrowDown />
        </chakraComponents.DropdownIndicator>
      ),
    };
  5. Integrate `chakra-react-select` with `react-hook-form`

    main

    Because chakra-react-select is not a native HTML input, you cannot use react-hook-form's default uncontrolled component pattern. Instead, you must use the Controller component or the useController hook to track the select's value in the form state.

    Common patterns include:

    • Using Controller for multi-select with built-in validation.
    • Using useController for single or multi-select.
    • Integrating with schema validation libraries like yup or zod.
  6. Run Chakra React Select Codemods

    main

    Use the crs-codemod tool to programmatically upgrade your codebase when features in chakra-react-select are deprecated. The codemods are powered by jscodeshift and allow you to apply large-scale changes without manual editing.

    To use the codemod, navigate to your project's root directory and run the command via npx.

    npx crs-codemod@latest <transform> <path>
  7. Upgrade from Version 5 (v5) using the v5 codemod

    main

    The v5 codemod automates the migration to version 5.0.0 of chakra-react-select. It targets all versions of the Select component, including:

    • Select
    • AsyncSelect
    • AsyncCreatableSelect
    • CreatableSelect

    Modifications performed:

    • Removes useBasicStyles prop: These styles are now the default.
    • Renames selectedOptionColor to selectedOptionColorScheme: This prop was renamed in v4.6.0 and removed in v5.0.0.
    • Renames colorScheme to tagColorScheme: Updated for better naming accuracy.
    • Removes hasStickyGroupHeaders prop: This prop was deprecated in v4.6.0 and removed in v5.0.0.

    Important Limitation: This codemod only works for props added directly to a Select instance. If you use a shared props object (e.g., const myProps = { ... }), you must apply these changes manually.

    npx crs-codemod@latest v5 .
    # or
    npx crs-codemod@latest v5 ./src
  8. Use TypeScript with chakra-react-select

    main

    The Select component uses three optional generics: Option, IsMulti, and Group. While TypeScript usually infers these automatically, you may need to provide them explicitly for complex custom types.

    This package exports several key types to assist with typing:

    • ChakraStylesConfig<Option, IsMulti, Group>: The type for the chakraStyles prop. It uses Chakra's SystemStyleObject instead of emotion styles.
    • OptionBase: A base type for individual options that includes custom props for styling selected options (e.g., variant, colorPalette, disabled). You should extend this for your custom option interfaces.
    • Component-specific types: SelectComponent, AsyncSelectComponent, CreatableSelectComponent, and AsyncCreatableSelectComponent.

    To ensure proper typing when using custom options, extend OptionBase and pass your interface as the first generic to the Select component.

    import { GroupBase, OptionBase, Select } from "chakra-react-select";
    
    interface ColorOption extends OptionBase {
      label: string;
      value: string;
      colorPalette?: string;
    }
    
    const colorOptions: ColorOption[] = [
      { label: "Red", value: "red", colorPalette: "red" },
      { label: "Blue", value: "blue" }
    ];
    
    function CustomMultiSelect() {
      return (
        <Select<ColorOption, true, GroupBase<ColorOption>>
          isMulti
          options={colorOptions}
          placeholder="Select some colors..."
        />
      );
    }
  9. Install chakra-react-select

    main

    To use chakra-react-select v6, you must first have @chakra-ui/react@3 installed and configured. This version is specifically updated for Chakra UI v3 and requires React 18 or above.

    1. Install Chakra UI dependencies:
    npm i @chakra-ui/react @emotion/react
    # or
    yarn add @chakra-ui/react @emotion/react
    1. Install chakra-react-select:
    npm i chakra-react-select
    # or
    yarn add chakra-react-select
    npm i @chakra-ui/react @emotion/react
    npm i chakra-react-select
  10. How to style the `menuPortal` component

    main

    The menuPortal key available in the original react-select styles prop is not available in chakraStyles because the MenuPortal is tightly integrated with Chakra's logic. If you are using menuPortalTarget, you have two options to style it:

    1. Use the original styles prop: Pass the menuPortal key via the styles prop. This is the only key from the original styles object that will be applied alongside chakraStyles.
    2. Use CSS with classNamePrefix: Pass a classNamePrefix and target the .prefix__menu-portal class in your CSS.
    // Option 1: Using the original styles prop
    <Select
      menuPortalTarget={document.body}
      styles={{
        menuPortal: (provided) => ({
          ...provided,
          zIndex: "var(--chakra-z-index-dropdown)",
        }),
      }}
      chakraStyles={{ /* other styles */ }}
    />
    
    // Option 2: Using classNamePrefix and CSS
    // React component:
    <Select menuPortalTarget={document.body} classNamePrefix="crs" />
    
    /* styles.css */
    .crs__menu-portal {
      z-index: var(--chakra-z-index-dropdown);
    }
  11. Run codemods with crs-codemod

    main

    The crs-codemod CLI is used to automate code transformations when updating chakra-react-select. It uses jscodeshift under the hood to apply specific transforms to your codebase.

    Usage

    You can run the codemod by providing the transform name and the target path directly, or by running the command without arguments to enter an interactive prompt.

    Direct Command:

    $ npx crs-codemod <transform> <path> <...options>

    Interactive Mode: If you run npx crs-codemod without arguments, the CLI will prompt you to select a transformer and specify the files or directories to target.

    Available Transforms

    • v5: Remove or replace deprecated props.
    # Example: Running the v5 transform on the src directory
    npx crs-codemod v5 src
  12. Customize tag colors with `tagColorPalette`

    main

    Use tagColorPalette to set a global color for all selected option tags. You can pass any valid Chakra color palette name.

    To override the global palette for a specific option, add a colorPalette key to that option's object in the options array.

    return (
      <Select
        {/* The global tag color palette */}
        tagColorPalette="purple"
        options={[
          {
            label: "I am red",
            value: "i-am-red",
            colorPalette: "red", // The option color palette overrides the global
          },
          {
            label: "I fallback to purple",
            value: "i-am-purple",
          },
        ]}
      />
    );