Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A Chakra UI themed wrapper for the popular library React Select

License

NotificationsYou must be signed in to change notification settings

csandman/chakra-react-select

Repository files navigation

This component is a wrapper for the popular react componentReact Select made using the UI libraryChakra UI.

Important

This version of Chakra React Select is updated forChakra UI v3 whichworks exclusively with React version 18 or above.Chakra React Select v5,which is compatible withChakra UI v2, will bemaintained for the foreseeable future. If you're still using Chakra UI v2checkthe docs for chakra-react-select v5 here.

Light ModeDark Mode
Light Mode DemoDark Mode Demo

Check out the demo here:

SB-TS

Note

Before leaving an issue on this project, remember that this is just awrapper forreact-select, not a standalone package. A large percentage ofthe questions people have end up being about howreact-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@3 set uplike in the guide in their docs.

npm i @chakra-ui/react @emotion/react# ...or...yarn add @chakra-ui/react @emotion/react

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, thecreatable 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 originalreact-select package are alsoexported from this package, so you can import any of them if you need them. Theonly exception is the rootSelect components.

Implementing this component in your application should be almost identical tohow you'd normally usereact-select. It willaccept all of the props that the original package does, with a few additions andexceptions listed below. So if you have a question on basic usage, your best betis to check the original docs or google "How to (some functionality) withreact-select" and just swap outreact-select withchakra-react-select inyour code.

Extra Props

All of the props from the originalreact-select package are also available inthis package, with a few exceptions. There are also some extra props that havebeen added to make this component behave/appear more like the built-in Chakra UIcomponents.

There are examples of all of the extra props below included inthe demo here.

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

You can pass thesize prop with eithersm,md, orlg. These will reflectthe sizes available on theChakra<Input /> component(except forxs because it's too small to work). Alternatively, you can pass aresponsive style array or objectofsize values to allow it to change depending on your theme's breakpoints.

If nosize is passed, it will default todefaultVariants.size from the themefor Chakra'sSelect component. If your component theme forSelect is notmodified, it will bemd.

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

Sizes


tagColorPalette

You can pass thetagColorPalette prop to the select component to change all ofthe selected options tags' colors. You can view the whole list of availablecolor palettes inthe Chakra docs, or if you havea custom color palette, any of the custom color names in that will be availableinstead.

Alternatively, you can add thecolorPalette key to any of your options objectsand it will only style that option when selected.

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",},]}/>);

Tag Color Palettes


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

You can pass thetagVariant prop with eithersubtle,solid, oroutline(default issubtle). These will reflect thevariant prop available on theChakra<Tag /> component.Alternatively, if you have added any custom variants to your theme, you can usethose instead.

Alternatively, you can add thevariant key to any of your options objects andit will only style that option when selected. This will override thetagVariant 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",},]}/>);

Tag Variants


invalid — Default:false |readOnly - Default:false

You can passinvalid to the select component to style it like the ChakraInput is styled when it receives the same prop. Alternatively, you can passreadOnly to make the component non-interactive in the same way Chakra'sInput does.

You can pass also passinvalid,disabled,readOnly, orrequired into awrappingField.Root (orField if using the snippet) to achieve the sameresult as passing these props into theSelect component. However, if you passthese props into theSelect component itself, that will override the propspassed into theField.Root.

In the migration toChakra v3,they ended up removing theinvalid prop from theInput,Select, andTextarea components themselves in favor of always having the user pass it intothe wrappingField.Root instead. However, it was decided that it wouldn't hurtto keep the prop on this component as well, as users don't always wrap theircomponents in aField.Root in the first place.

return(<>{/* This will show up with a red border */}<Selectinvalid/>{/* This will show up normally but will not be interactive */}<SelectreadOnly/>{/* 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 */}<Fieldlabel="Invalid & Disabled Select"invaliddisabledinvalidText="This error message shows because of an invalid Field.Root"><Select/></Field>{/* Or here's an example without using the snippet */}<Field.Rootinvaliddisabledrequired><Field.Label>        Invalid&DisabledSelect<Field.RequiredIndicator/></Field.Label><Select/><Field.ErrorText>        This error message shows because of an invalid Field.Root</Field.ErrorText></Field.Root></>);

Invalid/Disabled States


focusRingColor

The propfocusRingColor can be passed with Chakra color tokens which willemulate style the control component when focused.

return(<SelectfocusRingColor="blue.600"/>);

Orange errorBorderColor


selectedOptionStyle — Options:color |check — Default:color

You can pass the propselectedOptionStyle with either"color" or"check".The default option"color" will style a selected option similar to howreact-select does it, by highlighting the selected option in the color blue.Alternatively, if you pass"check" for the value, the selected option will bestyled like theChakra UI<Select /> componentand include a check icon on the right side of the selected option(s).

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

Color Highlighted Selected Option

Check Highlighted Selected Option


selectedOptionColorPalette — Default:blue

If you choose to stick with the defaultselectedOptionStyle="color", you haveone additional styling option. If you do not like the default of blue for thehighlight color, you can pass theselectedOptionColorPalette prop to changeit. This prop will accept any named color from your theme's color palette, andit will usecolorPalette.solid for the background, andcolorPalette.contrastfor the text.

If you'd like to use a custom color palette for this prop, ensure that you haveproperly set up the custom color, including thesolid andcontrast semantictokens, accoring tothe official guide.

Note

This prop can only be used for named colors from your theme, not arbitraryhex/rgb colors. If you would like to use a specific color for the backgroundthat's not a part of your theme, use thechakraStyles propto customize it (see#99 for anexample).

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

Purple Selected Option Color (light mode)

Purple Selected Option Color (dark mode)


variant — Options:outline |subtle — Default:outline

You can pass thevariant prop withoutline orsubtle to change the overallstyling of theSelect. These will reflect the various appearances availableforChakra's<Select /> component.Alternatively, if you've added any custom variants to your Chakra theme you canuse those instead. However, it is not guaranteed all styles will be applied howyou intend them to as there are some differences in the structure of theSelect's input component.

If novariant is passed, it will default todefaultProps.variant from thetheme for Chakra'sSelect component. If your component recipe forSelect isnot modified, it will beoutline.

The typing for this prop is actually pulled directly from your Chakra themeprops, so if you have any custom variants defined in your theme, you can usethose instead, and the typing will still work. That is, as long as you have runthetypegen commandto generate the new types.

return(<><Selectvariant="outline"/>{/* Default */}<Selectvariant="subtle"/></>);

variant in light mode

variant in dark mode


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

Styling

There are a few ways to style the components that make upchakra-react-select.It's important to note that this package does not use thetheme orstylesprops that are implemented inreact-select. Thetheme prop isn't used asmost of the components' base styles are pulling from your Chakra theme, andcustomizing 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 thestyles prop,chakraStyles. It mostly emulates the behavior of the originalstyles prop,however, because it’s not identical it is named differently to preventconfusion.

chakraStyles

To use thechakraStyles prop, first, check the documentation forthe originalstyles prop from the react-select docs.This package offers an identical API for thechakraStyles prop, however, theprovided and output style objects useChakra'scss propinstead of the default emotion styles the original package offers. This allowsyou to both use the shorthand styling props you'd normally use to style Chakracomponents, as well as tokens from your theme such as named colors.

The API for an individual style function looks like this:

/** *@param {SystemStyleObject} 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 {SystemStyleObject} An output style object which is forwarded to the component's `sx` prop */functionoption(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 thechakraStyles prop except formenuPortal. Along withsome other caveats, this is explained below.

Most of the components rendered by this package use the basicChakra<Box /> component witha few exceptions. Here are the style keys offered and the corresponding Chakracomponent that is rendered:

  • clearIndicator -Box (uses theme styles for Chakra'sselect.clearTrigger)
  • container -Box (uses theme styles for Chakra'sselect.root)
  • control -Box (uses theme styles for Chakra'sinput)
  • dropdownIndicator -Box (uses theme styles for Chrakra'sselect.indicator)
  • downChevron -chakra.svg (copied fromicons.tsx)
  • crossIcon -chakra.svg (copied fromicons.tsx)
  • group -Box (uses theme styles for Chakra'sselect.itemGroup)
  • groupHeading -Box (uses theme styles for Chakra'sselect.itemGroupLabel)
  • indicatorsContainer -Box (uses theme styles for Chakra'sselect.indicatorGroup)
  • indicatorSeparator -Separator
  • input -chakra.input (wrapped in aBox)
  • inputContainer -Box
  • loadingIndicator -Spinner
  • loadingMessage -Box
  • menu -Box
  • menuList -Box (uses theme styles for Chakra'sselect.content)
  • multiValue -Span (uses theme styles for Chakra'stag.root)
  • multiValueLabel -Span (uses theme styles for Chakra'stag.label)
  • multiValueEndElement -Box (uses theme styles for Chakra'stag.endElement. This is new to Chakra v3 due to the extra wrapping elementaround the close button)
  • multiValueRemove -Box (uses theme styles for Chakra'stag.closeTrigger)
  • noOptionsMessage -Box
  • option -Box (uses theme styles for Chakra'sselect.item)
  • placeholder -Box
  • singleValue -Box
  • valueContainer -Box

If you're using TypeScript, thechakraStyles prop is defined by the exportedChakraStylesConfig interface.

import{ChakraStylesConfig,Select}from"chakra-react-select";constApp:React.FC=()=>{constchakraStyles:ChakraStylesConfig={dropdownIndicator:(provided,state)=>({      ...provided,background:state.isFocused ?"blue.100" :provided.background,p:0,w:"40px",}),};return<SelectchakraStyles={chakraStyles}/>;};

Caveats

One change between the keys in thechakraStyles prop and the originalstylesprop, is that in the original theinput styles apply to a containersurrounding the HTML<input /> element, and there is no key for styling theinput itself. With thechakraStyles object, theinput key now styles theactual<chakra.input /> element and there is a new key,inputContainer, thatstyles the surroundingBox. Both functions use thestate argument for theoriginalinput key.

There are also two extra style keys for the icons contained within theindicators that are not offered in the original package. These aredownChevronwhich is contained inside theDropdownIndicator, and thecrossIcon which iscontained inside theClearIndicator. Both styles receive the samestatevalues as their containing indicators. These style keys were added as aconvenience, however you could also apply the same styles using the parentchakraStyles by doing something like this:

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

Additionally, there is one key that is available in thestyles prop that doesnot exist in thechakraStyles object;menuPortal. This key applies to theMenuPortal element which is only used when themenuPortalTarget prop is passedin. This component is replaceable, however, it is very tightly integrated withthe menu placement logic (and a context provider) so it appears to be impossibleto fully replace it with a chakra component. And in turn, it can't pull a keyfrom thechakraStyles prop. Therefore, if you are passing themenuPortalTarget prop and would like to change the styles of theMenuPortalcomponent, you have two options:

  1. Pass the originalstyles prop with themenuPortal key. This is the onlykey in thestyles object that will be applied to your components.
return(<SelectmenuPortalTarget={document.body}styles={{menuPortal:(provided)=>({        ...provided,// This is the z-index of the normal select in Chakra.zIndex:"var(--chakra-z-index-dropdown)",}),}}chakraStyles={{// All other component styles}}/>);
  1. Pass theclassNamePrefix propas described below and style theMenuPortal with CSS using the classNameprefix__menu-portal.
// example.jsimport"styles.css";return(<SelectmenuPortalTarget={document.body}classNamePrefix="crs"/>);
/* styles.css */.crs__menu-portal {z-index:var(--chakra-z-index-dropdown);}

If anyone has any suggestions for how to fully replace theMenuPortalcomponent, please leave a comment onthis issue orsubmit a pull request.

Theme Styles

As mentioned above, most of the custom components this package implements eitheruse styles from the globalChakra component recipes.As this package pulls directly from your Chakra theme, any changes you make tothose components' themes will modify the styles of the components in thispackage.

Note

Some of the theme styles are manually overridden when this package implementsthem. This is not as common as it used to be with Chakra V2 due to most stylesbeing pulled from theSelect slot recipe now, but there are a few othercases where this exception applies. There is no alternative to this currently,so if your custom theme styles are not being applied correctly please usechakraStyles to style your components instead.chakraStyles always takes the highest priority in overriding the styles of acomponent.

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

react-select componentchakra-ui
ClearIndicatorselect.clearTrigger
Controlinput
DropdownIndicatorselect.indicator
Groupselect.itemGroup
GroupHeadingselect.itemGroupLabel
IndicatorsContainerselect.indicatorGroup
LoadingIndicatorspinner
MenuListselect.content
MultiValueContainertag.root
MultiValueLabeltag.label
MultiValueRemovetag.endElement /tag.closeTrigger (this is a special case, because theMultiValueRemove renders both the aBox with thetag.endElement styles on it, as well as an innerBox with thetag.closeTrigger styles on it as it's direct child)
Optionselect.item
SelectContainerselect.root

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

Note

Only make changes to your global component themes if you want them to appearin all instances of that component. Otherwise, just change the individualcomponents' styles using thechakraStyles prop.

className

This package implements the same classNames on the sub components as theoriginal package so you can use these to style sub-components with CSS. Here isan excerpt fromthe react-select docsdescribing how it works:

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

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

For example, givenclassName='react-select-container' andclassNamePrefix="react-select", the DOM structure is similar to this:

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

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

TypeScript Support

This package has always supported typescript, however untilv3.0.0 none of thetype inference was working on the props passed into this component. Now thatthey are, you may need to pass in some generics for your component to be typedproperly, butin most cases you shouldn't need to because their types shouldbe inferred. Here is a snippet from the original documentation on the subject:

Select generics

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

https://react-select.com/typescript

Read theirfull documentation on thetopic for more info.

This package exports all of the named module members of the originalreact-select in case you need their built-in types in any of your variabledeclarations. The root selectProps type that is exported byreact-selecthas been extended using moduleaugmentation,[1][2]so if you import that type it will include all of the extra props offered. Thispackage also exports a few custom types that are specific to the custom propsoffered by this package:

  • ChakraStylesConfig<Option, IsMulti, Group> — The type for the propchakraStyles that can be passed to customize the component styles. This isalmost identical to the built-inStylesConfig type, however, it usesChakra'sSystemStyleObjecttype instead of react-select's emotion styles. It also has the same threegenerics as yourSelect component which would be required if you define yourstyles separately from your component.
  • OptionBase — A type for your individual select options that includes thecustom props for styling each of your selected options. This type is made togive you a base to extend off of and pass in as a generic to the rootSelectcomponent.
  • 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 tochakra-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 * * ``` * interface OptionBase { *   variant?: string; *   colorPalette?: string; *   disabled?: boolean; * }; * ``` */interfaceColorOptionextendsOptionBase{label:string;value:string;}constcolorOptions=[{label:"Red",value:"red",colorPalette:"red",// This is allowed because of the key in the `OptionBase` type},{label:"Blue",value:"blue",}]functionCustomMultiSelect(){return{<Select<ColorOption,true,GroupBase<ColorOption>>// <-- None of these generics should be requiredisMultiname="colors"options={colorOptions}placeholder="Select some colors..."/>}}

Customizing Components

Like the originalreact-select, this package exports all of the customcomponents that make up the overall select. However, instead of being exportedascomponents they are exported aschakraComponents to leave the originalcomponents export from react-select alone (you can import that as well ifyou'd like, however there shouldn't be any reason to). When implementing thiscomponent, you have the option to wrap these components and alter their stateand the children they returnin the same way the original does.

It's important to note, however, that there are 3 components offered in theoriginalreact-select that are missing fromchakraComponents. These are theCrossIcon,DownChevron, andMenuPortal. TheMenuPortal could not bereplaced at allas mentioned earlier, so if you'd like to customizeit, use the original from thecomponents import. The icons posed issues withprop compatibility when passing them into the coreSelect so the easiest wayto replace them would be to use a customDropdownIndicator orClearIndicatorand pass custom icons in as children:

import{typeGroupBase,typeSelectComponentsConfig,chakraComponents,}from"chakra-react-select";import{LuArrowDown,LuCircleX}from"react-icons/lu";interfaceOption{label:string;value:string;}constcomponents:SelectComponentsConfig<Option,true,GroupBase<Option>>={ClearIndicator:(props)=>(<chakraComponents.ClearIndicator{...props}><LuCircleX/></chakraComponents.ClearIndicator>),DropdownIndicator:(props)=>(<chakraComponents.DropdownIndicator{...props}><LuArrowDown/></chakraComponents.DropdownIndicator>),};

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

import{Box,Icon,useSlotRecipe}from"@chakra-ui/react";import{typeGroupBase,Select,typeSelectComponentsConfig,chakraComponents,}from"chakra-react-select";import{GiCherry,GiChocolateBar,GiCoffeeBeans,GiStrawberry,}from"react-icons/gi";interfaceFlavorOption{label:string;value:string;Icon:React.FC;iconColor:string;}constflavorOptions:FlavorOption[]=[{value:"coffee",label:"Coffee",Icon:GiCoffeeBeans,iconColor:"orange.700",},{value:"chocolate",label:"Chocolate",Icon:GiChocolateBar,iconColor:"yellow.800",},{value:"strawberry",label:"Strawberry",Icon:GiStrawberry,iconColor:"red.500",},{value:"cherry",label:"Cherry",Icon:GiCherry,iconColor:"red.600",},];constcustomComponents:SelectComponentsConfig<FlavorOption,true,GroupBase<FlavorOption>>={Option:({ children, ...props})=>(<chakraComponents.Option{...props}><Iconcolor={props.data.iconColor}boxSize={4}><props.data.Icon/></Icon><BoxflexGrow={1}>{children}</Box></chakraComponents.Option>),MultiValueContainer:({ children, ...props})=>{consttagStyles=useSlotRecipe({key:"tag"})();return(<chakraComponents.MultiValueContainer{...props}><Boxcss={tagStyles.startElement}color={props.data.iconColor}><props.data.Icon/></Box>{children}</chakraComponents.MultiValueContainer>);},};constOptionsWithIconsExample=()=>(<SelectisMultioptions={flavorOptions}placeholder="Select some flavors..."components={customComponents}/>);

Demos of both of the above examples can be found inthe main demo StackBlitz.

CustomLoadingIndicator (ChakraSpinner)

For most sub components, the styling can be easily accomplished using thechakraStyles prop. However, in the case of theLoadingIndicator there are a few props which do not directly correlate verywell with styling props. To solve that problem, thechakraComponents.LoadingIndicator component can be passed a few extra propswhich are normally available on the Chakra UISpinner. Here is anexample demonstrating which extra props are offered:

import{AsyncSelect,chakraComponents}from"chakra-react-select";// These are the defaults for each of the custom propsconstasyncComponents={LoadingIndicator:(props)=>(<chakraComponents.LoadingIndicator// The color palette of the filled in area of the spinner (there is no default)colorPalette="gray"// 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 propcolor="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 spinnertrackColor="transparent"// The `size` prop on the Chakra spinner// Defaults to one size smaller than the Select's sizespinnerSize="md"// A CSS <time> variable (s or ms) which determines the time it takes for the spinner to make one full rotationanimationDuration="500ms"// A CSS size string representing the thickness of the spinner's lineborderWidth="2px"// Don't forget to forward the props!{...props}/>),};constApp=()=>(<AsyncSelectisMultiname="colors"placeholder="Select some colors..."components={asyncComponents}loadOptions={(inputValue,callback)=>{setTimeout(()=>{constvalues=colorOptions.filter((i)=>i.label.toLowerCase().includes(inputValue.toLowerCase()));callback(values);},1500);}}/>);

useChakraSelectProps

Being a wrapper forreact-select, all of the customizations done toreact-select are passed in as props. There is a hook,useChakraSelectProps that handles mergingany extra customizations from the end user with the customizations done by thispackage. In some cases you may simply want to use this hook to get the customprops and pass them into areact-select instance yourself.

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

import{useState}from"react";import{useChakraSelectProps}from"chakra-react-select";importSelectfrom"react-select";import{options}from"./data";constCustomSelect=()=>{const[selectedOptions,setSelectedOptions]=useState([]);constselectProps=useChakraSelectProps({isMulti:true,value:selectedOptions,onChange:setSelectedOptions,});return<Select{...selectProps}/>;};

One important thing to note however, is that this hook generally adds no benefitif you're just going to pass the props it returns into the coreSelectcomponent from this package. The only time it really becomes useful is if you'repassing the resulting props into the corereact-select component, or anothercomponent that wraps it.

One example of how you might use this is to customize the componentreact-google-places-autocomplete, which is an autocomplete dropdown for GooglePlaces that uses theAsyncSelect fromreact-select as it's core. Therefore,it accepts all of the same select props as the core react-select does meaningyou can use theuseChakraSelectProps hook to style it:

import{useState}from"react";import{useChakraSelectProps}from"chakra-react-select";importGooglePlacesAutocompletefrom"react-google-places-autocomplete";constGooglePlacesAutocomplete=()=>{const[place,setPlace]=useState(null);constselectProps=useChakraSelectProps({value:place,onChange:setPlace,});return(<GooglePlacesAutocompleteapiKey="YOUR API KEY HERE"selectProps={selectProps}/>);};exportdefaultGooglePlacesAutocomplete;

Note

An API key would be needed to create a CodeSandbox example for this so youwill 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 Formin the same way you would with the original React Select, and the quickest wayto 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 thereact-selectcomponent in those examples with achakra-react-select component. However,here are a few examples to help you get started. If you'd like to see examplesusing other form providers, you cansubmit it as a Q&A discussion.

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

By default,react-hook-form usesuncontrolled componentsto reduced input renders however this only works for native HTML inputs. Becausechakra-react-select is not a native HTML input, you'll need to usereact-hook-form'sControllercomponent oruseControllerhook in order to keep the value(s) tracked inreact-hook-form's state. Hereare some examples using each:

Warning

These examples still need to be updated to the newest version ofchakra-react-select at some point, but they should still give you a goodidea of how to implement what you want.


Controller multi select with built-in validation

CS-JSCS-TS


useController multi select with built-in validation

CS-JSCS-TS


useController single select

CS-JSCS-TS


Multi select withyup validation (advanced example)

CS-JSCS-TS


Single select withyup validation (advanced example)

CS-JSCS-TS


Multi select withzod validation (advanced example)

CS-JSCS-TS


Single select withzod validation (advanced example)

CS-JSCS-TS


See this discussion for some examples of using this package withformik:#111

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 withyup validation

  • Vanilla JS:coming soon
  • TypeScript:coming soon

Templates

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


[8]ページ先頭

©2009-2025 Movatter.jp