Socket
Socket
Sign inDemoInstall

chakra-react-select

Package Overview
Dependencies
2
Maintainers
1
Versions
116
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    chakra-react-select

A chakra-ui wrapper for the popular select library react-select


Version published
Weekly downloads
114K
increased by1.48%
Maintainers
1
Created
Weekly downloads
 

Package description

What is chakra-react-select?

chakra-react-select is a package that integrates the popular react-select library with Chakra UI, providing a set of customizable and accessible select components that are styled using Chakra UI's design system.

What are chakra-react-select's main functionalities?

Basic Select

This code demonstrates a basic select component using chakra-react-select. It provides a dropdown with options for Chocolate, Strawberry, and Vanilla.

import React from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import { Select } from 'chakra-react-select';

const App = () => (
  <ChakraProvider>
    <Select
      options={[
        { value: 'chocolate', label: 'Chocolate' },
        { value: 'strawberry', label: 'Strawberry' },
        { value: 'vanilla', label: 'Vanilla' }
      ]}
    />
  </ChakraProvider>
);

export default App;

Multi-Select

This code demonstrates a multi-select component using chakra-react-select. It allows users to select multiple options from the dropdown.

import React from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import { Select } from 'chakra-react-select';

const App = () => (
  <ChakraProvider>
    <Select
      isMulti
      options={[
        { value: 'chocolate', label: 'Chocolate' },
        { value: 'strawberry', label: 'Strawberry' },
        { value: 'vanilla', label: 'Vanilla' }
      ]}
    />
  </ChakraProvider>
);

export default App;

Custom Styles

This code demonstrates how to apply custom styles to the select component using chakra-react-select. The control and options are styled with custom colors.

import React from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import { Select } from 'chakra-react-select';

const customStyles = {
  control: (provided) => ({
    ...provided,
    backgroundColor: 'lightblue'
  }),
  option: (provided, state) => ({
    ...provided,
    color: state.isSelected ? 'white' : 'black',
    backgroundColor: state.isSelected ? 'blue' : 'white'
  })
};

const App = () => (
  <ChakraProvider>
    <Select
      styles={customStyles}
      options={[
        { value: 'chocolate', label: 'Chocolate' },
        { value: 'strawberry', label: 'Strawberry' },
        { value: 'vanilla', label: 'Vanilla' }
      ]}
    />
  </ChakraProvider>
);

export default App;

Other packages similar to chakra-react-select

Readme

Source

chakra-react-select

MIT License npm - chakra-react-select bundle size - chakra-react-select bundle size - chakra-react-select Total Downloads - chakra-react-select

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 the demo here: https://codesandbox.io/s/chakra-react-select-demo-65ohb?file=/example.js

Usage

In order to use this package, you'll need to have @chakra-ui/react set up like in the guide in their docs. Then install this package:

npm i chakra-react-select

Then you can import the base select package, the async select, the creatable select or the async creatable select:

import {
  AsyncCreatableSelect,
  AsyncSelect,
  CreatableSelect,
  Select,
} from "chakra-react-select";

In order to use this component, you can implement it and use it like you would normally use react-select. It should accept almost all of the props that the original takes, with a few additions and exceptions.

Extra Props

  • 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 (with the exception of xs because it's too small to work).
return (
  <>
    <Select size="sm" />
    <Select size="md" /> {/* Default */}
    <Select size="lg" />
  </>
);
  • 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",
      },
    ]}
  />
);
  • 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 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",
      },
    ]}
  />
);
  • You can pass isInvalid to the select component to style it like the Chakra <Input /> is styled when it receives the same prop.
    • You can pass isInvalid or isDisabled to a <FormControl /> which surrounds this component and it will output their corresponding <Input /> styles.
return (
  <>
    {/* This will show up with a red border */}
    <Select isInvalid />

    {/* This will show up with a red border, and grayed out */}
    <FormControl isInvalid isDisabled>
      <FormLabel>Invalid & Disabled Select</FormLabel>
      <Select />
      <FormErrorMessage>
        This error message shows because of an invalid FormControl
      </FormErrorMessage>
    </FormControl>
  </>
);
  • One thing I added which isn't specific to Chakra or react-select is sticky group headers. It adds a border to the bottom of the header and keeps it in view while its corresponding group of options is visible. This can be very nice for when you have long lists of grouped options so you can always tell which group of options you're looking at. To add it, pass the hasStickyGroupHeaders prop to the select component.
return <Select hasStickyGroupHeaders />;

Sticky Group Headers

  • In your options objects, you can add the key isFixed: true to emulate the example in the react-select docs. This will prevent the options which have this flag from having the remove button on its corresponding tag. This only applies when using isMulti.
return (
  <Select
    isMulti
    options={[
      {
        label: "I can't be removed",
        value: "fixed",
        isFixed: true,
      },
      {
        label: "I can be removed",
        value: "not-fixed",
      },
    ]}
  />
);
  • In v1.3.0 you can now pass the prop selectedOptionStyle with either "color" or "check" (defaults to "color"). Until this version I had forgotten to style the selected options in the menu for both the single select, or the multi-select with hideSelectedOptions set to false. 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

  • 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 selectedOptionColor prop to change it. This prop will accept any named color from your color theme, and it will use the 500 value in light mode or the 300 value in dark mode.
return (
  <>
    <Select selectedOptionColor="blue" /> {/* Default */}
    <Select selectedOptionColor="purple" />
  </>
);

Purple Selected Option Color (light mode)

Purple Selected Option Color (dark mode)

  • 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 focusBorderColor="green.500" />
    <Select errorBorderColor="orange.500" />
  </>
);

Orange errorBorderColor

If you have any other questions or requests, leave it as an issue. I'm sure there are some features of react-select that I missed and I definitely want to make this wrapper as good as it can be!

Styling

There are a few methods of customizing the styles for this package. The first thing to note is that this package does not use the styles or theme props that are utilized by the original package. The theme prop isn't used as most of the base styles are set up to align with your Chakra theme, and customizing your base theme (such as colors or components) 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 with some slight tweaks, and because its not identical I decided it best to name it differently to avoid confusion.

chakraStyles

In order 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 {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
 */
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 here, except for input as that does not allow me to use the chakraStyles from the select props. The input styles are also much more dynamic and should be left alone for the most part.

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 - CloseButton
  • container - Box
  • control - Box (uses theme styles for Chakra's Input)
  • dropdownIndicator - Box (uses theme styles for Chrakra's InputRightAddon)
  • group - Box
  • groupHeading - Box (uses theme styles for Chakra's Menu group title)
  • indicatorsContainer - Box
  • indicatorSeparator - Divider
  • loadingIndicator - Spinner
  • loadingMessage - Box
  • menu - Box
  • menuList - Box (uses theme styles for Chakra's Menu)
  • multiValue - Tag
  • multiValueLabel - TagLabel
  • multiValueRemove - TagCloseButton
  • noOptionsMessage - Box
  • option - Box (uses theme styles for Chakra's MenuItem)
  • placeholder - Box
  • singleValue - Box
  • valueContainer - Box

If you're using typescript, define your chakraStyles object before passing it into your component using the ChakraStylesConfig type exported from this package:

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} />;
};

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. Here is a list of all components that will be affected by changes to your global styles:

react-select componentchakra-ui component styles
ClearIndicatorCloseButton
ControlInput
DropdownIndicatorInputRightAddon
GroupHeadingMenu group title
IndicatorSeparatorDivider
LoadingIndicatorSpinner
MenuListMenuList
MultiValueContainerTag
MultiValueLabelTagLabel
MultiValueRemoveTagCloseButton
OptionMenuItem

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: https://codesandbox.io/s/chakra-react-select-classnameprefix-demo-4r2pe?file=/example.js

CodeSandbox Templates

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

Roadmap

Since releasing this project, there have been a few things brought to my attention from users that I would like to update in the near future.

react-select v5

It was brought to my attention in this issue that react-select had a version 5 release almost immediately after I released this package (great timing right 😏). This version is rebuilt in TypeScript so you no longer need to install @types/react-select to access the types. I made a first pass at upgrading to the new version, and the errors I faced along with some comments I have been receiving from people have made me realize that I probably set up the types incorrectly when I first made this project. I still plan to make the switch soon, however I will need to take a deep dive into the inner workings of react-select's TypeScript support along with how TypeScript works itself, as i am very new to it. If anyone would like to help me make the upgrade/fix the way my types are implemented, I'd greatly appreciate it!

Keywords

FAQs

Last updated on 04 Jan 2022

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc