Git Product home page Git Product logo

chakra-react-select's Introduction

chakra-react-select v4

This version of chakra-react-select is updated for Chakra UI v2 which works exclusively with React v18. chakra-react-select v3 will be maintained until the majority of users have migrated. If you're still using Chakra UI v1 check the docs for chakra-react-select v3 here.

This component is a wrapper for the popular react component react-select made using the UI library Chakra UI.

Chakra React Select Banner

Check out these demos:

CS-JS-demo CS-TS-demo

NOTE: Before leaving an issue on this project, remember that this is just a wrapper for react-select, not a standalone package. A large percentage of the questions people have end up being about how react-select itself works, so please read through their documentation to familiarize yourself with it! https://react-select.com/home

Contents

Usage

To use this package, you'll need to have @chakra-ui/react@2 set up like in the guide in their docs. If you already have @chakra-ui/react@1 set up you can follow the steps in the official migration guide to update to v2. If you don't have Chakra UI installed already, you can install it like this:

npm i @chakra-ui/react @emotion/react@^11.8.1 @emotion/styled@^11 framer-motion@^6
# ...or...
yarn add @chakra-ui/react @emotion/react@^11.8.1 @emotion/styled@^11 framer-motion@^6

NOTE: As of v3.3.3, your project will need to have a minimum of @emotion/[email protected] installed to avoid having multiple copies of @emotion/react installed. For more info, see PR #115.

After Chakra UI is set up, install this package from NPM:

npm i chakra-react-select
# ...or...
yarn add chakra-react-select

Once installed, you can import the base select package, the async select, the creatable select or the async creatable select like so:

import {
  AsyncCreatableSelect,
  AsyncSelect,
  CreatableSelect,
  Select,
} from "chakra-react-select";
// ...or...
const {
  AsyncCreatableSelect,
  AsyncSelect,
  CreatableSelect,
  Select,
} = require("chakra-react-select");

All exports, including types, from the original react-select package are also exported from this package, so you can import any of them if you need them. The only exception is the root Select components.

Implementing this component in your application should be almost identical to how you'd normally use react-select. It will accept all of the props that the original package does, with a few additions and exceptions listed below. So if you have a question on basic usage, your best bet is to check the original docs or google "How to (some functionality) with react-select" and just swap out react-select for chakra-react-select.

Extra Props

size — Options: ResponsiveValue<"sm" | "md" | "lg"> — Default: md

You can pass the size prop with either sm, md, or lg (default is md). These will reflect the sizes available on the Chakra <Input /> component (except for xs because it's too small to work). Alternatively, you can pass a responsive style array or object of size values to allow it to change depending on your theme's breakpoints.

If no size is passed, it will default to defaultProps.size from the theme for Chakra's Input component. If your component theme for Input is not modified, it will be md.

return (
  <>
    <Select size="sm" />
    <Select size="md" /> {/* Default */}
    <Select size="lg" />
  </>
);

CS-JS


colorScheme

You can pass the colorScheme prop to the select component to change all of the selected options tags' colors. You can view the whole list of available color schemes in the Chakra docs, or if you have a custom color palette, any of the custom color names in that will be available instead.

Alternatively, you can add the colorScheme key to any of your options objects and it will only style that option when selected.

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

CS-JS


tagVariant — Options: subtle | solid | outline — Default: subtle

You can pass the tagVariant prop with either subtle, solid, or outline (default is subtle). These will reflect the variant prop available on the Chakra <Tag /> component. Alternatively, if you have added any custom variants to your theme, you can use those instead.

Alternatively, you can add the variant key to any of your options objects and it will only style that option when selected. This will override the tagVariant prop on the select if both are set

return (
  <Select
    {/* The global variant */}
    tagVariant="solid"
    options={[
      {
        label: "I have the outline style",
        value: "i-am-outlined",
        variant: "outline", // The option variant overrides the global
      },
      {
        label: "I fallback to the global `solid`",
        value: "i-am-solid",
      },
    ]}
  />
);

CS-JS


isInvalid — Default: false | isReadOnly - Default: false

You can pass isInvalid to the select component to style it like the Chakra Input is styled when it receives the same prop. Alternatively, you can pass isReadOnly to make the component non-interactive in the same way Chakra's Input does.

You can pass also pass isInvalid, isDisabled, or isReadOnly into a wrapping <FormControl /> to achieve the same result as passing these props into the Select component.

return (
  <>
    {/* This will show up with a red border */}
    <Select isInvalid />

    {/* This will show up normally but will not be interactive */}
    <Select isReadOnly />

    {/* This will show up grayed out and will not be interactive */}
    {/* Additionally, it will have a red border and the error message will be shown */}
    <FormControl isInvalid isDisabled>
      <FormLabel>Invalid & Disabled Select</FormLabel>
      <Select />
      <FormErrorMessage>
        This error message shows because of an invalid FormControl
      </FormErrorMessage>
    </FormControl>
  </>
);

CS-JS


focusBorderColor — Default: blue.500 | errorBorderColor — Default: red.500

The props focusBorderColor and errorBorderColor can be passed with Chakra color strings which will emulate the respective props being passed to Chakra's <Input /> component.

return (
  <>
    <Select errorBorderColor="orange.500" isInvalid />
    <Select focusBorderColor="green.500" />
  </>
);

Orange errorBorderColor

CS-JS


useBasicStyles — Default: false

If this prop is passed, the dropdown indicator at the right of the component will be styled in the same way the original Chakra Select component is styled, instead of being styled as an InputRightAddon. The original purpose of styling it as an addon was to create a visual separation between the dropdown indicator and the button for clearing the selected options. However, as this button only appears when isMulti is passed, using this style could make more sense for a single select.

return <Select useBasicStyles />;

useBasicStyles

useBasicStyles dark mode

CS-JS


selectedOptionStyle — Options: color | check — Default: color

As of v1.3.0 you can pass the prop selectedOptionStyle with either "color" or "check". The default option "color" will style a selected option similar to how react-select does it, by highlighting the selected option in the color blue. Alternatively, if you pass "check" for the value, the selected option will be styled like the Chakra UI Menu component and include a check icon next to the selected option(s). If isMulti and selectedOptionStyle="check" are passed, space will only be added for the check marks if hideSelectedOptions={false} is also passed.

return (
  <>
    <Select selectedOptionStyle="color" /> {/* Default */}
    <Select selectedOptionStyle="check" /> {/* Chakra UI Menu Style */}
  </>
);

Color Highlighted Selected Option

Check Highlighted Selected Option

CS-JS


selectedOptionColorScheme — Default: blue

If you choose to stick with the default selectedOptionStyle="color", you have one additional styling option. If you do not like the default of blue for the highlight color, you can pass the selectedOptionColorScheme prop to change it. This prop will accept any named color from your theme's color palette, and it will use the 500 value in light mode or the 300 value in dark mode.

NOTE: This prop can only be used for named colors from your theme, not arbitrary hex/rgb colors. If you would like to use a specific color for the background that's not a part of your theme, use the chakraStyles prop to customize it (see #99 for an example).

Prior to v4.6.0 this prop was named selectedOptionColor, and it was renamed to prevent confusion about its purpose. selectedOptionColor is still available but will be removed in the next major version.

return (
  <>
    <Select selectedOptionColorScheme="blue" /> {/* Default */}
    <Select selectedOptionColorScheme="purple" />
  </>
);

Purple Selected Option Color (light mode)

Purple Selected Option Color (dark mode)

CS-JS


variant — Options: outline | filled | flushed | unstyled — Default: outline

You can pass the variant prop with any of outline, filled, flushed, or unstyled to change the overall styling of the Select. These will reflect the various appearances available for Chakra's <Input /> component. Alternatively, if you've added any custom variants to your Chakra theme you can use those instead. However, it is not guaranteed all styles will be applied how you intend them to as there are some differences in the structure of the Select's input component.

If no variant is passed, it will default to defaultProps.variant from the theme for Chakra's Input component. If your component theme for Input is not modified, it will be outline.

return (
  <>
    <Select variant="outline" /> {/* Default */}
    <Select variant="filled" />
    <Select variant="flushed" />
    <Select variant="unstyled" />
  </>
);

variant in light mode

variant in dark mode

By default, the flushed and unstyled variants look a bit strange in combination with the DropdownIndicator. An easy way to make these styles look more natural is to pass the useBasicStyles prop along with them to remove the background from the indicator. Alternatively, you could hide the indicator completely using chakraStyles.

variant with useBasicStyles

Another thing to note is that the default styling for variant="filled" and isMulti results in the select and selected option tags having the same background color when the select is not focused. The easiest solution for this is to pass the tagVariant or colorScheme prop to add some contrast between the two elements.

variant with useBasicStyles

CS-JS


If you have any other requests for Chakra-like features that could be added, or problems with the current features, please start a discussion!

Styling

There are a few ways to style the components that make up chakra-react-select. It's important to note that this package does not use the theme or styles props that are implemented in react-select. The theme prop isn't used as most of the components' base styles are pulling from your Chakra theme, and customizing your base theme (such as colors or component styles) should in turn change the styles in this package.

This package does however offer an alternative to the styles prop, chakraStyles. It mostly emulates the behavior of the original styles prop, however, because it’s not identical it is named differently to prevent confusion.

chakraStyles

To use the chakraStyles prop, first, check the documentation for the original styles prop from the react-select docs. This package offers an identical API for the chakraStyles prop, however, the provided and output style objects use Chakra's sx prop instead of the default emotion styles the original package offers. This allows you to both use the shorthand styling props you'd normally use to style Chakra components, as well as tokens from your theme such as named colors.

The API for an individual style function looks like this:

/**
 * @param {CSSObject} provided -- The component's default Chakra styles
 * @param {Object} state -- The component's current state e.g. `isFocused` (this gives all of the same props that are passed into the component)
 * @returns {CSSObject} An output style object which is forwarded to the component's `sx` prop
 */
function option(provided, state) {
  return {
    ...provided,
    color: state.isFocused ? "blue.500" : "red.400",
  };
}

All of the style keys offered in the original package can be used in the chakraStyles prop except for menuPortal. Along with some other caveats, this is explained below.

Most of the components rendered by this package use the basic Chakra <Box /> component with a few exceptions. Here are the style keys offered and the corresponding Chakra component that is rendered:

  • clearIndicator - Box (uses theme styles for Chakra's CloseButton)
  • container - Box
  • control - Box (uses theme styles for Chakra's Input)
  • dropdownIndicator - Box (uses theme styles for Chrakra's InputRightAddon)
  • downChevron - Icon
  • crossIcon - Icon
  • group - Box
  • groupHeading - Box (uses theme styles for Chakra's Menu group title)
  • indicatorsContainer - Box
  • indicatorSeparator - Divider
  • input - chakra.input (wrapped in a Box)
  • inputContainer - Box
  • loadingIndicator - Spinner
  • loadingMessage - Box
  • menu - Box
  • menuList - Box (uses theme styles for Chakra's Menu)
  • multiValue - chakra.span (uses theme styles for Chakra's Tag)
  • multiValueLabel - chakra.span (uses theme styles for Chakra's TagLabel)
  • multiValueRemove - Box (uses theme styles for Chakra's TagCloseButton)
  • noOptionsMessage - Box
  • option - Box (uses theme styles for Chakra's MenuItem)
  • placeholder - Box
  • singleValue - Box
  • valueContainer - Box

If you're using TypeScript, the chakraStyles prop is defined by the exported ChakraStylesConfig interface.

import { ChakraStylesConfig, Select } from "chakra-react-select";

const App: React.FC = () => {
  const chakraStyles: ChakraStylesConfig = {
    dropdownIndicator: (provided, state) => ({
      ...provided,
      background: state.isFocused ? "blue.100" : provided.background,
      p: 0,
      w: "40px",
    }),
  };

  return <Select chakraStyles={chakraStyles} />;
};

Caveats

One change between the keys in the chakraStyles prop and the original styles prop, is that in the original the input styles apply to a container surrounding the HTML <input /> element, and there is no key for styling the input itself. With the chakraStyles object, the input key now styles the actual <chakra.input /> element and there is a new key, inputContainer, that styles the surrounding Box. Both functions use the state argument for the original input key.

There are also two extra style keys for the icons contained within the indicators that are not offered in the original package. These are downChevron which is contained inside the DropdownIndicator, and the crossIcon which is contained inside the ClearIndicator. Both styles receive the same state values as their containing indicators. These style keys were added as a convenience, however you could also apply the same styles using the parent chakraStyles by doing something like this:

const chakraStyles = {
  dropdownIndicator: (prev, { selectProps }) => ({
    ...prev,
    "> svg": {
      transform: `rotate(${selectProps.menuIsOpen ? -180 : 0}deg)`,
    },
  }),
};

CS-JS

Additionally, there is one key that is available in the styles prop that does not exist in the chakraStyles object; menuPortal. This key applies to the MenuPortal element which is only used when the menuPortalTarget prop is passed in. This component is replaceable, however, it is very tightly integrated with the menu placement logic (and a context provider) so it appears to be impossible to fully replace it with a chakra component. And in turn, it can't pull a key from the chakraStyles prop. Therefore, if you are passing the menuPortalTarget prop and would like to change the styles of the MenuPortal component, you have two options:

  1. Pass the original styles prop with the menuPortal key. This is the only key in the styles object that will be applied to your components.
return (
  <Select
    menuPortalTarget={document.body}
    styles={{
      menuPortal: (provided) => ({ ...provided, zIndex: 100 }),
    }}
    chakraStyles={
      {
        // All other component styles
      }
    }
  />
);
  1. Pass the classNamePrefix prop as described below and style the MenuPortal with CSS using the className prefix__menu-portal.
// example.js
import "styles.css";

return (
  <Select
    menuPortalTarget={document.body}
    classNamePrefix="chakra-react-select"
  />
);
/* styles.css */

.chakra-react-select__menu-portal {
  z-index: 100;
}

If anyone has any suggestions for how to fully replace the MenuPortal component, please leave a comment on this issue or submit a pull request.

Examples

Dropdown menu attached to control example:

CS-JS CS-TS

Default Chakra <Select /> styles example:

CS-JS CS-TS

NOTE: This can now be accomplished with the useBasicStyles prop

Theme Styles

As mentioned above, a few of the custom components this package implements either use styles from the global Chakra component theme or are themselves those components. As this package pulls directly from your Chakra theme, any changes you make to those components' themes will propagate to the components in this package.

NOTE: Some of the theme styles are manually overridden when this package implements them. This is necessary for implementing styles for size variants in components that do not natively have them in Chakra's default theme. This mostly concerns components that make up the Menu, but there are a few other cases where this exception applies. There is no alternative to this currently, so if your custom theme styles are not being applied correctly please use chakraStyles to style your components instead. chakraStyles always takes the highest priority in overriding the styles of a component. See #194 for more info.

Here is a list of all components that will be affected by changes to your theme:

react-select component chakra-ui component styles
ClearIndicator CloseButton
Control Input
DropdownIndicator InputRightAddon
GroupHeading Menu group title
LoadingIndicator Spinner
MenuList MenuList
MultiValueContainer Tag
MultiValueLabel TagLabel
MultiValueRemove TagCloseButton
Option MenuItem

In addition to specific component styles, any changes you make to your global color scheme will also be reflected in these custom components.

NOTE: Only make changes to your global component themes if you want them to appear in all instances of that component. Otherwise, just change the individual components' styles using the chakraStyles prop.

className

This package implements the same classNames on the sub components as the original package so you can use these to style sub-components with CSS. Here is an excerpt from the react-select docs describing how it works:

If you provide the className prop to react-select, the SelectContainer will be given a className based on the provided value.

If you provide the classNamePrefix prop to react-select, all inner elements will be given a className with the provided prefix.

For example, given className='react-select-container' and classNamePrefix="react-select", the DOM structure is similar to this:

<div class="react-select-container">
  <div class="react-select__control">
    <div class="react-select__value-container">...</div>
    <div class="react-select__indicators">...</div>
  </div>
  <div class="react-select__menu">
    <div class="react-select__menu-list">
      <div class="react-select__option">...</div>
    </div>
  </div>
</div>

While we encourage you to use the new Styles API, you still have the option of styling via CSS classes. This ensures compatibility with styled components, CSS modules and other libraries.

Here is an example of using classNames to style the components:

CS-JS

TypeScript Support

This package has always supported typescript, however until 3.0.0 none of the type inference was working on the props passed into this component. Now that they are, you may need to pass in some generics for your component to work properly, but in most cases you shouldn't need to. Here is a snippet from the original documentation on the subject:

Select generics

There are three generics used by the Select component: Option, IsMulti, and Group. All of them are optional and TypeScript attempts to detect them automatically, but sometimes it might need some help. Many of the react-select types include the three generics like this:

https://react-select.com/typescript

Read their full documentation on the topic for more info.

This package exports all of the named module members of the original react-select in case you need their built-in types in any of your variable declarations. The root select Props type that is exported by react-select has been extended using module augmentation,[1][2] so if you import that type it will include all of the extra props offered. This package also exports a few custom types that are specific to the custom props offered by this package:

  • ChakraStylesConfig — The type for the prop chakraStyles that can be passed to customize the component styles. This is almost identical to the built-in StylesConfig type, however, it uses Chakra's CSSObject type instead of react-select's emotion styles.
  • OptionBase — A type for your individual select options that includes the custom props for styling each of your selected options. This type is made to give you a base to extend off of and pass in as a generic to the root Select component.
  • Each of the four Select components has a type exported with it:
    • SelectComponent
    • AsyncSelectComponent
    • CreatableSelectComponent
    • AsyncCreatableSelectComponent

Here is an example of how to pass in the proper generics to chakra-react-select:

import { GroupBase, OptionBase, Select } from "chakra-react-select";

/**
 * `OptionBase` is a custom type exported by this package meant to be extended
 * to make your custom option types. It includes all of the keys that can be
 * used by this package to customize the styles of your selected options
 *
 * ```
 * type OptionBase = {
 *   variant?: string;
 *   colorScheme?: string;
 *   isDisabled?: boolean;
 * };
 * ```
 */
interface ColorOption extends OptionBase {
  label: string;
  value: string;
}

const colorOptions = [
  {
    label: "Red",
    value: "red",
    colorScheme: "red", // This is allowed because of the key in the `OptionBase` type
  },
  {
    label: "Blue",
    value: "blue",
  }
]

function CustomMultiSelect() {
  return {
    <Select<ColorOption, true, GroupBase<ColorOption>> // <-- None of these generics should be required
      isMulti
      name="colors"
      options={colorOptions}
      placeholder="Select some colors..."
    />
  }
}

Customizing Components

Like the original react-select, this package exports all of the custom components that make up the overall select. However, instead of being exported as components they are exported as chakraComponents to leave the original components export from react-select alone (you can export that as well if you'd like). When implementing this component, you have the option to wrap these components and alter their state and the children they return in the same way the original does.

It's important to note, however, that there are 3 components offered in the original react-select that are missing from chakraComponents. These are the CrossIcon, DownChevron, and MenuPortal. The MenuPortal could not be replaced at all as mentioned earlier, so if you'd like to customize it, use the original from the components import. The icons posed issues with prop compatibility when passing them into the core Select so the easiest way to replace them would be to use a custom DropdownIndicator or ClearIndicator and pass custom icons in as children:

const components = {
  ClearIndicator: (props) => (
    <chakraComponents.ClearIndicator {...props}>
      <Icon as={IoMdCloseCircleOutline} w={4} h={4} />
    </chakraComponents.ClearIndicator>
  ),
  DropdownIndicator: (props) => (
    <chakraComponents.DropdownIndicator {...props}>
      <Icon as={AiFillCaretDown} />
    </chakraComponents.DropdownIndicator>
  ),
};

CS-JS

Here's a complete example of how you might use custom components to create a select with a custom Option:

import { Icon } from "@chakra-ui/react";
import { Select, chakraComponents } from "chakra-react-select";
import {
  GiCherry,
  GiChocolateBar,
  GiCoffeeBeans,
  GiStrawberry,
} from "react-icons/gi";

const flavorOptions = [
  {
    value: "coffee",
    label: "Coffee",
    icon: <Icon as={GiCoffeeBeans} color="orange.700" mr={2} h={5} w={5} />,
  },
  {
    value: "chocolate",
    label: "Chocolate",
    icon: <Icon as={GiChocolateBar} color="yellow.800" mr={2} h={5} w={5} />,
  },
  {
    value: "strawberry",
    label: "Strawberry",
    icon: <Icon as={GiStrawberry} color="red.500" mr={2} h={5} w={5} />,
  },
  {
    value: "cherry",
    label: "Cherry",
    icon: <Icon as={GiCherry} color="red.600" mr={2} h={5} w={5} />,
  },
];

// Make sure this is defined outside of the component which returns your select
// or you'll run into rendering issues
const customComponents = {
  Option: ({ children, ...props }) => (
    <chakraComponents.Option {...props}>
      {props.data.icon} {children}
    </chakraComponents.Option>
  ),
};

const Example = () => (
  <Select
    name="flavors"
    options={flavorOptions}
    placeholder="Select some flavors..."
    components={customComponents}
  />
);

CS-JS CS-TS

Custom LoadingIndicator (Chakra Spinner)

For most sub components, the styling can be easily accomplished using the chakraStyles prop. However, in the case of the LoadingIndicator there are a few props which do not directly correlate very well with styling props. To solve that problem, the chakraComponents.LoadingIndicator component can be passed a few extra props which are normally available on the Chakra UI Spinner. Here is an example demonstrating which extra props are offered:

import { AsyncSelect, chakraComponents } from "chakra-react-select";

// These are the defaults for each of the custom props
const asyncComponents = {
  LoadingIndicator: (props) => (
    <chakraComponents.LoadingIndicator
      // The color of the main line which makes up the spinner
      // This could be accomplished using `chakraStyles` but it is also available as a custom prop
      color="currentColor" // <-- This default's to your theme's text color (Light mode: gray.700 | Dark mode: whiteAlpha.900)
      // The color of the remaining space that makes up the spinner
      emptyColor="transparent"
      // The `size` prop on the Chakra spinner
      // Defaults to one size smaller than the Select's size
      spinnerSize="md"
      // A CSS <time> variable (s or ms) which determines the time it takes for the spinner to make one full rotation
      speed="0.45s"
      // A CSS size string representing the thickness of the spinner's line
      thickness="2px"
      // Don't forget to forward the props!
      {...props}
    />
  ),
};

const App = () => (
  <AsyncSelect
    isMulti
    name="colors"
    placeholder="Select some colors..."
    components={asyncComponents}
    loadOptions={(inputValue, callback) => {
      setTimeout(() => {
        const values = colourOptions.filter((i) =>
          i.label.toLowerCase().includes(inputValue.toLowerCase())
        );
        callback(values);
      }, 3000);
    }}
  />
);

CS-JS CS-TS

useChakraSelectProps

Being a wrapper for react-select, all of the customizations done to react-select are passed in as props. There is a hook, useChakraSelectProps that handles merging any extra customizations from the end user with the customizations done by this package. In some cases you may simply want to use this hook to get the custom props and pass them into a react-select instance yourself.

To do so, simply import the hook from this package, and call it by passing in any extra custom props you'd like into it and spread it onto a base react-select component:

import { useState } from "react";
import { useChakraSelectProps } from "chakra-react-select";
import Select from "react-select";
import { options } from "./data";

const CustomSelect = () => {
  const [selectedOptions, setSelectedOptions] = useState([]);

  const selectProps = useChakraSelectProps({
    isMulti: true,
    value: selectedOptions,
    onChange: setSelectedOptions,
  });

  return <Select {...selectProps} />;
};

One example of how you might use this is to customize the component react-google-places-autocomplete, which is an autocomplete dropdown for Google Places that uses the AsyncSelect from react-select as it's core. Therefore, it accepts all of the same select props as the core react-select does meaning you can use the useChakraSelectProps hook to style it:

import { useState } from "react";
import { useChakraSelectProps } from "chakra-react-select";
import GooglePlacesAutocomplete from "react-google-places-autocomplete";

const GooglePlacesAutocomplete = () => {
  const [place, setPlace] = useState(null);

  const selectProps = useChakraSelectProps({
    value: place,
    onChange: setPlace,
  });

  return (
    <GooglePlacesAutocomplete
      apiKey="YOUR API KEY HERE"
      selectProps={selectProps}
    />
  );
};

export default GooglePlacesAutocomplete;

NOTE: An API key would be needed to create a CodeSandbox example for this so you will have to implement it in your own project if you'd like to test it out.

Usage with React Form Libraries

This section is a work in progress, check back soon for more examples

This package can be used with form controllers such as Formik or React Hook Form in the same way you would with the original React Select, and the quickest way to figure out how to do so would be to Google something along the lines of "react-select with formik/react-hook-form/etc" and replace react-select in those examples with chakra-react-select. However, here are a few examples to help you get started. If you'd like to see examples using other form providers, you can submit it as a Q&A discussion.

See this issue for some discussion about using this package with react-hook-form: #7

By default, react-hook-form uses uncontrolled components to reduced input renders however this only works for native HTML inputs. Because chakra-react-select is not a native HTML input, you'll need to use react-hook-form's Controller component or useController hook in order to keep the value(s) tracked in react-hook-form's state. Here are some examples using each:

Controller multi select with built-in validation

CS-JS CS-TS

useController multi select with built-in validation

CS-JS CS-TS

useController single select

CS-JS CS-TS

Multi select with yup validation (advanced example)

CS-JS CS-TS

Single select with yup validation (advanced example)

CS-JS CS-TS

Multi select with zod validation (advanced example)

CS-JS CS-TS

Single select with zod validation (advanced example)

CS-JS CS-TS

See this issue for some discussion about using this package with formik: #23

Single select with built-in validation

  • Vanilla JS: coming soon
  • TypeScript: coming soon

Multi select with built-in validation

  • Vanilla JS: coming soon
  • TypeScript: coming soon

Multi select with yup validation

  • Vanilla JS: coming soon
  • TypeScript: coming soon

CodeSandbox Templates

When submitting a bug report, please include a minimum reproduction of your issue using one of these templates:

chakra-react-select's People

Contributors

caitlinsweeney avatar csandman avatar imgbotapp avatar jackhumphries9 avatar jonashger avatar malinskibeniamin avatar paescuj avatar vntguva avatar vtv6 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chakra-react-select's Issues

[BUG] dark mode dropdown issues

Description

added this package and was expecting dark mode to work out of the box. But as you can see the options are not visible. Any idea how i can style the options background manually? Can't seem to select it using inspect element

Screenshot 2022-05-23 at 11 18 52 PM

chakra-react-select Version

4.0.0

Link to Reproduction

No response

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Go to '...'
  2. Click on '...'
  3. Scroll down to '...'
  4. See error

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

Exported Types Wrong?

Thanks for creating this component. However, the types shipped with the component reuse the Chakra props of Select, rather than the different props that react-select use (for example, isMulti is not supported and you can't set the options).

[BUG] Unable to focus or search using React Production mode.

Describe the bug
Using the dev build of react, my select component works perfectly.
However, once I go to prod build, the component is unable to be focused and search no longer works.
I went through the dom and the only difference I can find is that on the dev build, the following element exists:
image

All of the other Chakra components works 100% fine, it's just the chakra-react-select component.
Is there any known issue with production builds or minifying?

To Reproduce
Steps to reproduce the behavior:
Can't provide reproduction since it would require a production build.
I'm using create-react-app so really there shouldn't be any weirdness.

Desktop (please complete the following information):

  • OS: Mac
  • Browser Chrome
  • Version 1.8.7 (but i checked older versions and the issue remains)

Additional context
I'm assuming other people aren't having issues with this, but there's no reason that only this library is affected.
The only thing I can think of is some unlisted dependency issue.
Any tips would be greatly appreciated.

[QUESTION] Props in custom component

My question is...
Hi dev!

I would like to ask for some help in creating a custom component with the chakra-react-select in typescript. I'm struggling with the Select props in my component, because the props are not showing up in the custom component.

Can you please provide a code example?

I appreciate your attention!

[BUG] Input color in dark mode is not visible.

Describe the bug
When using the latest build (2.0.0) switching to dark mode, the input text is un-readable. Attempting to change the color with theme props, doesn't work.

Link to Reproduction
A link to a CodeSandbox with a minimal reproduction of the bug you're experiencing.

Fork one of these template projects to get started:

To Reproduce
Steps to reproduce the behavior:

  • Switch to dark mode
  • Type in the input box

Expected behavior
To be able to see text being submitted

Screenshots
image

Desktop (please complete the following information):
All platforms.

Additional context
Switching back to 1.3.4 fixed the issue.

[BUG] When using Select component inside a Modal component from Chakra UI V2

Description

Hello,

I am using the Select component inside of a Chakra UI Modal component.
Everything works as expected until the moment I close the Modal and re-open it.

The selections are gone when the Modal is re-opened. However, it appears that the value state is still saved because when I create: const [selectValue, setSelectValue] = useState([]);
Then I update the state with an onChange={(event) => setSelectValue(event)} and then read that state when opening the modal again it appears to be saved.

chakra-react-select Version

4.0.0

Link to Reproduction

https://codesandbox.io/s/chakra-ui-react-select-forked-1rmcdb

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Open the modal with the "Open Modal"-button
  2. Select some things into the Select component
  3. Close the modal
  4. Open the modal

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

use with formik

Is your feature request related to a problem? Please describe.
I tried to use this with Formik. But I couldn't get it to work as a drop in replacement fromthe normal chakra ui select.

Describe the solution you'd like
If this is already implemented, I would love an example. If not, what's the point of a Select without it being useful for forms.

Describe alternatives you've considered
I searched how people do that with react select, but I couldn't do it.

Here is my code, it works with the normal Chakra UI Select.

<Field name="subject" validate={validateSubject}>
  {({ field, form }: FieldProps) => (
    <FormControl
      isInvalid={!!form.errors.subject && !!form.touched.subject}
      isRequired
    >
      <FormLabel mt="4">Subject</FormLabel>
      <Select
        {...field}
        id="subject"
        placeholder="Select subject.."
        options={options}
        rounded="4"
      />
      <FormErrorMessage>{form.errors.subject}</FormErrorMessage>
    </FormControl>
  )}
</Field>

But I get this error with the new select.

Unhandled Runtime Error

TypeError: target is undefined
Call Stack
useFormik/executeChange<
node_modules\formik\dist\formik.esm.js (721:0)
useFormik/handleChange<
node_modules\formik\dist\formik.esm.js (755:0)
useEventCallback/<
node_modules\formik\dist\formik.esm.js (1256:0)

[QUESTION] zIndex when using menuPortalTarget

Hey,
is there a way to change the zIndex when using a portal to move the dropdown to document.body?
In react-select there's the styles property where you can customize CSS of the portal, like this:

<Select menuPortalTarget={document.body} styles={{menuPortal: (provided) => {...provided, zIndex: 100} }}/>

Unfortunately, the menuPortal property doesn't seem to exist in chakra-react-select in chakraStyles. Is there any way to change the zIndex on the portal?

Deselecting item when disabled

Description

If the selection is disabled (isDisabled={true}), the selected option can still be deselected by clicking on the cross.

image

chakra-react-select Version

2.0.0

Link to Reproduction

No response

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Select some items
  2. Disable select
  3. Deselect them by clicking on the cross

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

[BUG] When upgrading to React18/Chakra2: createStylesContext is not a function

Description

After upgrading to React 18 / Chakra v2 I am hitting one last issue from this package. I am seeing this message:

(0 , _chakra_ui_system__WEBPACK_IMPORTED_MODULE_1__.createStylesContext) is not a function

I've tried rolling back but just get useContext errors. Any tips here would be great; I'd love to complete this upgrade :)

 >  NX   Report complete - copy this into the issue template

   Node : 16.15.1
   OS   : darwin arm64
   yarn : 1.22.19

   nx : 14.4.2
   @nrwl/angular : Not Found
   @nrwl/cypress : 14.4.2
   @nrwl/detox : Not Found
   @nrwl/devkit : 14.4.2
   @nrwl/eslint-plugin-nx : 14.4.2
   @nrwl/express : Not Found
   @nrwl/jest : 14.4.2
   @nrwl/js : 14.4.2
   @nrwl/linter : 14.4.2
   @nrwl/nest : Not Found
   @nrwl/next : Not Found
   @nrwl/node : 14.4.2
   @nrwl/nx-cloud : 14.2.0
   @nrwl/nx-plugin : Not Found
   @nrwl/react : 14.4.2
   @nrwl/react-native : Not Found
   @nrwl/schematics : Not Found
   @nrwl/storybook : 14.4.2
   @nrwl/web : 14.4.2
   @nrwl/workspace : 14.4.2
   typescript : 4.7.4
   ---------------------------------------

package.json

{
  "name": "flowpath",
  "version": "0.0.0",
  "license": "none",
  "scripts": {
    "postinstall": "tsc -p tools/tsconfig.tools.json"
  },
  "private": true,
  "engines": {
    "node": ">= 16.0.0",
    "npm": ">= 6.0.0",
    "yarn": ">= 1.0.0"
  },
  "dependencies": {
    "@amcharts/amcharts5": "^5.2.10",
    "@amcharts/amcharts5-geodata": "^5.0.3",
    "@appsignal/javascript": "^1.3.23",
    "@appsignal/react": "^1.0.20",
    "@chakra-ui/icons": "^2.0.4",
    "@chakra-ui/react": "^2.2.4",
    "@dnd-kit/core": "^6.0.5",
    "@dnd-kit/modifiers": "^6.0.0",
    "@dnd-kit/sortable": "^7.0.1",
    "@dnd-kit/utilities": "^3.2.0",
    "@emotion/react": "11.9.3",
    "@emotion/styled": "11.9.3",
    "@fontsource/nunito-sans": "^4.5.8",
    "@fortawesome/fontawesome-svg-core": "6.1.1",
    "@fortawesome/pro-light-svg-icons": "6.1.1",
    "@fortawesome/pro-solid-svg-icons": "6.1.1",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "@hookform/resolvers": "^2.9.6",
    "@khanacademy/react-multi-select": "^0.3.3",
    "@loadable/component": "^5.15.2",
    "@react-hook/window-size": "^3.0.7",
    "@react-hookz/web": "^15.0.1",
    "@splitsoftware/splitio-react": "^1.6.0",
    "@storybook/builder-webpack5": "6.5.9",
    "@storybook/core-server": "6.4.22",
    "@storybook/manager-webpack5": "6.5.9",
    "@tanstack/react-location": "^3.7.4",
    "@tanstack/react-virtual": "^3.0.0-beta.2",
    "@trendmicro/react-sidenav": "^0.5.0",
    "axios": "^0.27.2",
    "boring-avatars": "^1.7.0",
    "buffer": "^6.0.3",
    "chakra-react-select": "4.1.3",
    "change-case": "^4.1.2",
    "chroma-js": "^2.4.2",
    "classnames": "^2.3.1",
    "core-js": "^3.21.1",
    "d3": "^7.3.0",
    "date-fns": "^2.28.0",
    "downshift": "^6.1.7",
    "formik": "^2.2.9",
    "framer-motion": "^6.5.1",
    "html5-qrcode": "^2.2.1",
    "http-status-codes": "^2.2.0",
    "interactjs": "^1.10.11",
    "just-debounce-it": "^3.0.1",
    "lodash.debounce": "^4.0.8",
    "lodash.isempty": "^4.4.0",
    "lodash.isequal": "^4.5.0",
    "md5": "^2.3.0",
    "moment": "^2.29.3",
    "moment-timezone": "^0.5.34",
    "notification-service-js": "^0.6.2",
    "pluralize": "^8.0.0",
    "pondjs": "^0.9.0",
    "query-string": "^7.1.1",
    "randomcolor": "^0.6.2",
    "rc-time-picker": "^3.7.3",
    "react": "18.2.0",
    "react-accessible-accordion": "^3.3.5",
    "react-autocomplete-input": "^1.0.18",
    "react-beautiful-dnd": "^13.1.0",
    "react-big-calendar": "^0.40.1",
    "react-calendar-timeline": "^0.27.0",
    "react-code-blocks": "^0.0.9-0",
    "react-collapsible": "^2.8.4",
    "react-confirm-alert": "^2.8.0",
    "react-csv": "^2.2.2",
    "react-date-range": "^1.4.0",
    "react-datepicker": "^4.8.0",
    "react-dates": "^21.8.0",
    "react-datetime-picker": "^3.5.0",
    "react-debounce-input": "^3.2.5",
    "react-dom": "18.2.0",
    "react-dropdown-tree-select": "^2.7.1",
    "react-dropzone": "^14.2.2",
    "react-fade-in": "^2.0.1",
    "react-fast-compare": "^3.2.0",
    "react-floating-action-button": "^1.0.5",
    "react-fullstory": "^1.4.0",
    "react-google-recaptcha": "^2.1.0",
    "react-grid-layout": "^1.3.4",
    "react-highlight-words": "^0.18.0",
    "react-hook-form": "^7.33.1",
    "react-html5-camera-photo": "^1.5.10",
    "react-images-upload": "^1.2.8",
    "react-images-uploading": "^3.1.7",
    "react-is": "18.2.0",
    "react-linkify": "^1.0.0-alpha",
    "react-linkify-it": "^1.0.7",
    "react-loading": "^2.0.3",
    "react-loading-overlay": "^1.0.1",
    "react-map-gl": "^6.1.17",
    "react-minimal-pie-chart": "^8.2.0",
    "react-modal": "^3.15.1",
    "react-multi-date-picker": "^3.3.0",
    "react-number-format": "^4.9.3",
    "react-qr-code": "^2.0.7",
    "react-query": "^3.39.2",
    "react-recaptcha": "^2.3.10",
    "react-redux": "8.0.2",
    "react-router": "^6.3.0",
    "react-router-dom": "6.3.0",
    "react-select": "^5.2.2",
    "react-show-more-text": "^1.5.2",
    "react-sweet-progress": "^1.1.2",
    "react-table": "^7.8.0",
    "react-table-v6": "^6.8.6",
    "react-tag-autocomplete": "^6.2.0",
    "react-tag-input": "^6.8.0",
    "react-textarea-autosize": "^8.3.4",
    "react-timeseries-charts": "^0.16.1",
    "react-to-print": "^2.14.7",
    "react-tooltip": "^4.2.21",
    "react-transition-group": "^4.4.2",
    "react-use": "^17.4.0",
    "react-use-intercom": "^2.0.0",
    "react-vis": "^1.11.7",
    "react-weekly-day-picker": "^1.0.3",
    "react-window-size": "^1.2.2",
    "reactjs-popup": "^2.0.5",
    "redux": "^4.1.1",
    "redux-logger": "^3.0.6",
    "redux-persist": "^6.0.0",
    "redux-promise": "^0.6.0",
    "redux-thunk": "^2.3.0",
    "regenerator-runtime": "0.13.9",
    "rooks": "^5.11.8",
    "styled-components": "5.3.5",
    "three": "0.142.0",
    "tslib": "^2.0.0",
    "us-zips": "^2021.11.4",
    "use-places-autocomplete": "^4.0.0",
    "vanta": "^0.5.22",
    "webpack-retry-chunk-load-plugin": "^3.1.1",
    "workbox-core": "^6.5.3",
    "workbox-expiration": "^6.5.3",
    "workbox-precaching": "^6.5.3",
    "workbox-routing": "^6.5.3",
    "workbox-strategies": "^6.5.3",
    "workbox-webpack-plugin": "^6.5.3",
    "yup": "^0.32.11",
    "zod": "^3.17.3",
    "zxcvbn": "^4.4.2"
  },
  "devDependencies": {
    "@babel/core": "7.18.6",
    "@babel/preset-typescript": "7.18.6",
    "@chakra-ui/cli": "^2.1.2",
    "@faker-js/faker": "^7.3.0",
    "@hookform/devtools": "^4.2.2",
    "@netlify/functions": "^1.0.0",
    "@nrwl/cli": "14.4.2",
    "@nrwl/cypress": "14.4.2",
    "@nrwl/eslint-plugin-nx": "14.4.2",
    "@nrwl/jest": "14.4.2",
    "@nrwl/js": "14.4.2",
    "@nrwl/linter": "14.4.2",
    "@nrwl/node": "14.4.2",
    "@nrwl/nx-cloud": "14.2.0",
    "@nrwl/react": "14.4.2",
    "@nrwl/storybook": "14.4.2",
    "@nrwl/web": "14.4.2",
    "@nrwl/workspace": "14.4.2",
    "@playwright/test": "^1.23.3",
    "@snek-at/storybook-addon-chakra-ui": "^1.0.0",
    "@storybook/addon-essentials": "6.5.9",
    "@storybook/react": "6.5.9",
    "@svgr/webpack": "^6.2.1",
    "@tanstack/react-location-devtools": "^3.4.4",
    "@testing-library/react": "13.3.0",
    "@types/jest": "27.4.1",
    "@types/moment": "^2.13.0",
    "@types/node": "18.0.0",
    "@types/react": "18.0.15",
    "@types/react-dom": "18.0.6",
    "@types/react-grid-layout": "^1.3.2",
    "@types/react-is": "17.0.3",
    "@types/react-router-dom": "5.3.3",
    "@types/styled-components": "5.1.25",
    "@typescript-eslint/eslint-plugin": "5.30.6",
    "@typescript-eslint/parser": "5.30.6",
    "@welldone-software/why-did-you-render": "^7.0.1",
    "babel-jest": "28.1.3",
    "babel-loader": "8.2.5",
    "babel-plugin-styled-components": "2.0.7",
    "copyfiles": "^2.4.1",
    "cors": "^2.8.5",
    "csstype": "^3.0.11",
    "cypress": "^8.3.0",
    "eslint": "8.15.0",
    "eslint-config-prettier": "^8.5.0",
    "eslint-import-resolver-typescript": "^2.5.0",
    "eslint-plugin-cypress": "^2.10.3",
    "eslint-plugin-deprecation": "^1.3.2",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-jsdoc": "^39.3.3",
    "eslint-plugin-jsx-a11y": "6.6.0",
    "eslint-plugin-prefer-arrow": "^1.2.3",
    "eslint-plugin-react": "7.30.1",
    "eslint-plugin-react-hooks": "4.6.0",
    "express": "^4.18.1",
    "helmet": "^4.6.0",
    "heroku-ssl-redirect": "^0.1.1",
    "jest": "27.5.1",
    "namor": "^2.0.4",
    "node-fetch": "^3.2.8",
    "nx": "14.4.2",
    "prettier": "2.7.1",
    "prettier-plugin-sh": "^0.12.6",
    "react-test-renderer": "18.2.0",
    "source-map-explorer": "^2.5.2",
    "ts-jest": "27.1.4",
    "typescript": "4.7.4",
    "url-loader": "^4.1.1",
    "webpack-bundle-analyzer": "^4.5.0",
    "webpack-merge": "^5.8.0",
    "webpack-stats-plugin": "^1.0.3"
  }
}

chakra-react-select Version

4.1.3

Link to Reproduction

Of course this is a private repo so no public repro 😞

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Build app

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

image

[QUESTION] Eliminate unnecessary dependencies

I use the package @chakra-ui/react and it contains all the packages that I get the warning message

warning " > [email protected]" has unmet peer dependency "@chakra-ui/form-control@^1.0.0".        
warning " > [email protected]" has unmet peer dependency "@chakra-ui/icon@^2.0.0".
warning " > [email protected]" has unmet peer dependency "@chakra-ui/layout@^1.0.0".
warning " > [email protected]" has unmet peer dependency "@chakra-ui/menu@^1.0.0".
warning " > [email protected]" has unmet peer dependency "@chakra-ui/spinner@^1.0.0".
warning " > [email protected]" has unmet peer dependency "@chakra-ui/system@^1.2.0".

can you remove them in upcoming updates

[BUG] type become "unknown" whenever i use charkaStyles or styles prop

Description

When i use the chakraStyles property or the styles property, the inferred type throughout the whole component becomes unknown.
I would have expected this to not make any difference to the inferred type.

Works fine without:
image

Unknown type:
image

chakraStyles:
image

chakra-react-select Version

3.3.3

TypeScript?

  • Yes I use TypeScript

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

[FEATURE] react-hook-form support

It would be great if this component would support react-hook-form, so that you can set an error validation or policy like a normal chakra ui select with {...register}, e.g. whether the field is required or not.

Colors not working in demos

Describe the bug
The "select colors" examples do not display colors correctly.

Example: "Select Colors and Flavours / md" example -- all selections are grey.

Example: "Select Colors and Flavours / with global" -- all selections are purple.

Link to Reproduction

The demos you list from this repo's README:

To Reproduce
Steps to reproduce the behavior:

  1. Visit either demo sandbox
  2. Click a few options in each example

Expected behavior
Each selection should use the color of the name selected, as in the README screen shot.

Screenshots
image

Desktop (please complete the following information):

  • OS: OSX
  • Browser: Chrome 98.0.4758.102

[BUG] Select blurs when it is used in other clickable element

Description

Screen.Recording.2022-07-29.at.17.45.17.mov

chakra-react-select Version

4.1.4

Link to Reproduction

No response

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Go to '...'
  2. Click on '...'
  3. Scroll down to '...'
  4. See error

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

[BUG] Type 'true' is not assignable to type 'false'

Am having issues with the isMulti property of the chakra react's select. The isMulti works when am not defining any styles object attached to the component, but if I defined some styling object extending the ChakraStyleConfig. Then typescript beings to frown to the isMulti Property.
This is my code below...

const SelectComponent = ({
  label,
  options,
  placeholder,
  isMultiple,
  handleChange,
}: IProps) => {

  const chakraStyles: ChakraStylesConfig = {
    container: (provided, state) => ({
      ...provided,
      border: "0.3px solid",
      borderColor: state.isFocused ? "blue.300" : "black",
      _hover: {
        borderColor: "ash.300",
      },
      _active: {
        borderColor: "blue.300",
      },
      borderRadius: "5px",
      outline: "transparent",
    }),
    control: (provided, state) => ({
      ...provided,
      border: "none",
      background: "none",
      fontSize: "15px",
    }),
    input: (provided, state) => ({
      ...provided,
      fontSize: "15px",
    }),
  };

  return (
    <FormControl w="full">
      <FormLabel color="#718096" fontSize="13px" fontWeight="600" mb="5px">
        {label}
      </FormLabel>
      <Select
        isMulti
        name="colors"
        focusBorderColor="blue.300"
        placeholder={placeholder}
        options={options}
        onChange={(e: any) => handleChange(e)}
        chakraStyles={chakraStyles}
      />
    </FormControl>
  );
};

This is the image of the warning typescript wants me to fix
warning

So after removing the chakraStyles
nowarning

I dont know what is going on or what am doing wrong, Kindly help

[BUG] Can't add custom props for MenuList via innerProps

Description

When I add custom properties on innerProps for MenuList (like data-testid) they are ignored. It seems they aren't exploded in MenuList component. The original react-select library allows that.

chakra-react-select Version

3.3.7

Link to Reproduction

https://codesandbox.io/s/react-select-playground-forked-nqwxik?file=/src/index.tsx

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

No response

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

[BUG] Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Description

chakra-react-select requires @chakra-ui/react: 2.2.1. It breaks on @chakra-ui/react: 2.2.0

chakra-react-select Version

4.0.1

Link to Reproduction

https://codesandbox.io/s/naughty-visvesvaraya-i8b13i?file=/pages/index.tsx

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Go to '...'
  2. Click on '...'
  3. Scroll down to '...'
  4. See error

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

[BUG] Latest build doesn't include types

Description

It looks like types weren't included beyond 3.3.3.

chakra-react-select Version

3.3.3

Link to Reproduction

No response

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Install chakra-react-select
  2. View node-modules/chakra-react-select/dist
  3. Observe types directory missing

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

[QUESTION] Cannot read properties of undefined (reading 'value') - i18n locales

I'd like to change the locale: "en" and "pl" but I occured an error Cannot read properties of undefined (reading 'value')
here

  const changeLanguage = e => {
> 63 |     const locale = e.target.value
     |                            ^
  64 |     router.push(router.pathname, router.asPath, { locale })
  65 |   }

changing the locale logic

const Navbar = props => {
  const { path } = props
  const router = useRouter()
  const { locale } = router
  const t = locale === 'en' ? en : pl

  const changeLanguage = e => {
    const locale = e.target.value
    router.push(router.pathname, router.asPath, { locale })
  }

Here is my Select component

<Select
  onChange={changeLanguage}
  defaultValue={locale}
  width="74px"
  display={{ base: 'none', md: 'inline-block' }}
  variant="outline"
  cursor="pointer"
  ml="30px"
  options={[
    {
      label: 'EN',
      value: 'en'
    },
    {
      label: 'PL',
      value: 'pl'
    }
  ]}
/>

the previous one chakra's one orginal which worked

<Select
  onChange={changeLanguage}
  defaultValue={locale}
  width="74px"
  display={{ base: 'none', md: 'inline-block' }}
  variant="outline"
  cursor="pointer"
  ml="30px"
  _focus={{
    boxShadow: 'teal'
  }}
>
  <option value="en">EN</option>
  <option value="pl">PL</option>
</Select>

[QUESTION] Adding floating labels to Creatable Select

Hi ! Thanks for this wonderful library that has made dropdowns much more robust and easy to work with :)
I would just like to know if there was some way of including floating labels with the Creatable Select component? This is what i have done so far

import { extendTheme } from "@chakra-ui/react"

const activeLabelStyles = {
    transform: 'scale(0.85) translateY(-24px)',
}

export const theme = extendTheme({
    components: {
        Form: {
            variants: {
                floating: {
                    container: {
                        _focusWithin: {
                            label: {
                                ...activeLabelStyles,
                            },
                        },
                        'input:not(:placeholder-shown) + label, .chakra-select__wrapper + label, .react-date-picker + label': {
                            ...activeLabelStyles,
                        },
                        label: {
                            top: 0,
                            left: 0,
                            zIndex: 2,
                            position: 'absolute',
                            backgroundColor: 'white',
                            pointerEvents: 'none',
                            mx: 3,
                            px: 1,
                            my: 2,
                            transformOrigin: 'left top'
                        },
                    },
                },
            },
        },
    },
})

Unfortunately, the placeholder covers up the selected value when focus leaves the component, and I haven't been able to figure out a way to apply the above theme to the CreatableSelect. This is what my CreatableSelect looks like :

<FormControl id="place" isRequired>
    <FormLabel>Place</FormLabel>
    <CreatableSelect size='xl'
        name="place"
        options={locality}
        closeMenuOnSelect={true}
        value={place}
        tabSelectsValues
        onChange={setPlace}
        openMenuOnFocus
        placeholder={"Select/Type a place"}
    />
</FormControl>

[QUESTION] How to set defaultValue with styles?

Default values are not given the appropriate color

image

 <FormControl p={4}>
  <FormLabel>Select Tag</FormLabel>
  <Select
    size="lg"
    isMulti
    name="colors"
    options={mappedOptions}
    placeholder="Select some tags"
    closeMenuOnSelect={false}
    onChange={handleSetSelectedOptions}
    defaultValue={[mappedOptions[1]]}

  />
</FormControl>

[BUG] menuIsOpen broken in 4.2.1

Description

Looks like the changes in 4.2.1 for read-only behaviour broke the controlled functionality of react-select.

minimal repro: https://codesandbox.io/s/chakra-react-select-menuisopen-fjzmyt?file=/src/App.tsx

changing the dep to 4.2.0 in that CSB shows it working as intended

thanks!

chakra-react-select Version

4.2.1

Link to Reproduction

https://codesandbox.io/s/chakra-react-select-menuisopen-fjzmyt?file=/src/App.tsx

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. set menuIsOpen to true
  2. menu is not open

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

No response

[BUG] CreatableSelect with onCreateOption prop has a bug

Describe the bug
If you use CreatableSelect with onCreateOption, <CreatableSelect onCreateOption={...} /> to create a new option, the created value is not displayed.

Link to Reproduction
https://codesandbox.io/s/chakra-react-select-oncreateoption-cy2ko

You can confirm that react-select has no problem with that.
https://codesandbox.io/s/z19sm
https://react-select.com/creatable

To Reproduce
Steps to reproduce the behavior:

  1. Go to the reproduction link
  2. Type anything to create an option then enter
  3. The inputted value is not displayed

Expected behavior
The created value should be displayed.

Thanks.

[BUG] ESM No matching export for import "MultiValueProps"

Describe the bug
When upgrading to v3 we are seeing the following build error for ESM (using ViteJS as a build runner):

node_modules/chakra-react-select/dist/esm/types.js:2:9: error: No matching export in "node_modules/react-select/dist/react-select.esm.js" for import "MultiValueProps"

Additional context
If we remove/comment out the line import { MultiValueProps } from "react-select"; in dist/ems/types.js everything works as expected

[BUG] Ordering style issue on @emotion/css or @emotion/react when call any component form chakra-react-select

Describe the bug
This issue happened when call any component from chakra-react-select to your codes. Normally we can easily overwrite Chakra-UI Provider default Theme but after calling any component from chakra-react-select it changed the ordering and cause emotion become unable to overwrite the styling

How To Reproduce
This bugs only happened when you start calling any chakra-react-select component to your codes, if you only install it won't change anything

Expected behavior
Expected chakra-ui default style to be low priority

Screenshots
[Before]
image

[After]
image

[BUG]

Description

When I press the tab key while a select list is open I expect the next focusable element to be focused. Instead, items from the list are added to the current selection.

chakra-react-select Version

4.1.3

Link to Reproduction

https://codesandbox.io/s/chakra-react-select-vsvr0?file=/example.js

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. Go to https://codesandbox.io/s/chakra-react-select-vsvr0?file=/example.js
  2. Tab into select
  3. Press down arrow to open list
  4. Press tab a few times

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

Peek 2022-07-26 16-33

Support for react hook form

The component seems to break when attempting to validate the number of inputs using the register function in react hook form. Is it possible for you to add support for react hook form?

[QUESTION] Is there a way to support larger Size properties?

Thanks for the good work with this component.

In my chakra-ui project, I had to create xl, 2xl and 3xl properties for Button and Input. I'm mainly changing height, paddingX and fontSize between those sizes because I just want a bigger elements.

Scanning through chakra-react-select code I realized that there is only support for the default chakra-ui props. Is there any way to support for other sizes? The docs says that xs was too small, but besides that, can the component just extend those properties from the main theme?

Long term support

Please don't take offense :) It looks as though commits are regular etc. On a scale of 1-10 can you give me an idea as to commitment? Have a large project I'm considering using this lib in. Happy to contrib etc. Just wondering if author is currently using in production. Honestly no wrong answer here. Thanks in advance.

[BUG] Multi-select with a custom component has broken focus

Describe the bug
A clear and concise description of what the bug is.

Link to Reproduction
A link to a CodeSandbox with a minimal reproduction of the bug you're experiencing.
https://codesandbox.io/s/chakra-react-select-custom-option-forked-cglhg?file=/example.js:1662-2098

Steps to reproduce

  1. Have a multi selector, with a custom component, and a state controlled value. (value={selectedValues}).
  2. Select a value from the selector, then try to click off of the menu to close the select menu.
  3. Notice it's impossible to close the select menu unless you click the select button again. It will remain in focus in the background and cause problems for other components.

Expected behavior
The select menu closes when you click off the menu, and focus is removed.

Screenshots
image

Desktop (please complete the following information):

  • OS: MacOS
  • Browser Chrome

[FEATURE] Please exported out all Select Interface

Describe the solution you'd like
I want to create custom component in my project with this chakra-react-select. I need the interface for all Select props so i can make it become a component. I need it as soon as possible. Thanks!

isReadOnly doesn't work

Description

When property isReadOnly={true} select is still editable

chakra-react-select Version

4.1.5

Link to Reproduction

No response

TypeScript?

  • Yes I use TypeScript

Steps to reproduce

  1. set isReadOnly={true}
  2. try to edit the select

Operating System

  • macOS
  • Windows
  • Linux
  • iOS/iPadOS
  • Android

Additional Information

I fixed this issue by wrapping component in div with style pointerEvents: "none"

[BUG] React Hook form - reset not working

Describe the bug
When calling the reset function of the react hook form the input continues with the selected values.

Link to Reproduction
https://codesandbox.io/s/chakra-react-select-react-hook-form-usecontroller-forked-cjo82?file=/example.js

To Reproduce
Steps to reproduce the behavior:

  1. Go to codesandbox
  2. Fill the form
  3. See the bug

Expected behavior
the select input should be empty

Desktop (please complete the following information):

  • OS: Windows
  • Browser: chrome
  • Version: ^3.0.3

[QUESTION] regarding styling

My question is...
I want to change colors & other css properties, even classNamePrefix of react-select isn't working with the component, menu list doesn't get the prefix

Installing the library causes emotion error

Installing this library and using it in conjuncture with either next.js or storybook causes emotions errors during the startup of dev servers.

Using next.js I get this error:

next-translate - compiled page: /albums/new - locale: en - namespaces: common - used loader: getStaticProps
error - TypeError: stylis.middleware is not a function
    at Object.createCache [as default] (/Users/johannesklauss/Documents/Github/Syra/node_modules/@emotion/react/node_modules/@emotion/cache/dist/emotion-cache.cjs.dev.js:331:30)
    at EmotionGlobal (/Users/johannesklauss/Documents/Github/Syra/node_modules/@emotion/react/dist/emotion-element-ce965253.cjs.dev.js:59:48)
    at processChild (/Users/johannesklauss/Documents/Github/Syra/node_modules/react-dom/cjs/react-dom-server.node.development.js:3353:14)
    at resolve (/Users/johannesklauss/Documents/Github/Syra/node_modules/react-dom/cjs/react-dom-server.node.development.js:3270:5)
    at ReactDOMServerRenderer.render (/Users/johannesklauss/Documents/Github/Syra/node_modules/react-dom/cjs/react-dom-server.node.development.js:3753:22)
    at ReactDOMServerRenderer.read (/Users/johannesklauss/Documents/Github/Syra/node_modules/react-dom/cjs/react-dom-server.node.development.js:3690:29)
    at Object.renderToString (/Users/johannesklauss/Documents/Github/Syra/node_modules/react-dom/cjs/react-dom-server.node.development.js:4298:27)
    at Object.renderPage (/Users/johannesklauss/Documents/Github/Syra/node_modules/next/dist/server/render.js:596:45)
    at Function.getInitialProps (webpack-internal:///../../node_modules/next/dist/pages/_document.js:194:19)
    at Object.loadGetInitialProps (/Users/johannesklauss/Documents/Github/Syra/node_modules/next/dist/shared/lib/utils.js:69:29)

Using storybook I get this error:

bootstrap:27 Uncaught TypeError: (0 , stylis__WEBPACK_IMPORTED_MODULE_0__.middleware) is not a function
    at createCache (emotion-cache.browser.esm.js:287)
    at Object../node_modules/@emotion/react/dist/emotion-element-99289b21.browser.esm.js (emotion-element-99289b21.browser.esm.js:17)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Object../node_modules/@emotion/styled-base/dist/styled-base.browser.esm.js (emotion-serialize.browser.esm.js:314)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)
    at Object../node_modules/@storybook/theming/node_modules/@emotion/styled/dist/styled.browser.esm.js (memoize.browser.esm.js:9)
    at __webpack_require__ (bootstrap:24)
    at fn (hot module replacement:61)

The weirdest thing is that this also happens when I am not even using the library. Only when I remove the library the errors go away.

I have the following setup (the next.js app gets bundled with webpack5):

"@chakra-ui/react": "1.6.10",
"@emotion/react": "11.5.0",
"@emotion/server": "11.4.0",
"@emotion/styled": "11.3.0",
"chakra-react-select": "1.3.2",
"framer-motion": "4.1.17",
"next": "11.1.2",
"react": "17.0.2",
"react-dom": "17.0.2",

And I am using Storybook with webpack5:

"@storybook/addon-essentials": "6.3.0",
"@storybook/addon-knobs": "6.3.1",
"@storybook/addon-links": "6.3.0",
"@storybook/builder-webpack5": "6.3.0",
"@storybook/manager-webpack5": "6.3.0",
"@storybook/react": "6.3.0",

Chakra itself works fine and is correctly setup. Only after installing this library the error occurs. Any idea what might causing it?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.