How to create a React Select Component with Typescript and a collection of objects?

About

This page shows you a minimal example of the React Select library (a React select element) with Typescript.

Usage

React select can handle any list of objects.

The essential props are:

  • options to define the list of objects
  • getOptionValue to define the value
  • getOptionLabel to define the label
import Select, {Props} from "react-select";

export type BookType = {
    id: string
    name: string
    author: string
    publisher: string
}

export function BookSelect({books, defaultBook}:{books:BookType[], defaultBook?:BookType}) {

   const selectProps: Props<BookType, false> =
	{
		options: books, // a list of objects in our case of Books
		onChange: (book) => {
			if (!book) {
				return;
			}
			console.log(`The book ${book.name} was chosen`);
		},
		getOptionLabel: (book) => book.name, // label definition
		getOptionValue: (book) => book.id, // value definition
		// not defaultValue otherwise, it does not rerender
		value: defaultBook // default value
	}
   return (
	<Select<BookType, false> {...selectProps}/>
   )
}

Support

Error TS2322

When starting, you may get the TS2322 error,

TS2322: 
Type '{ style: CSSProperties | undefined; className: string; 'aria-errormessage'?: string | undefined; 
'aria-invalid'?: boolean | "false" | "true" | "grammar" | "spelling" | undefined; ... 70 more ...; 
defaultValue?: PropsValue<...> | undefined; }' 
is not assignable to type 
'Omit<PublicBaseSelectProps<BookType, false, GroupBase<BookType>>, StateManagedPropKeys>'.

Types of property 'isMulti' are incompatible.
Type 'boolean | undefined' is not assignable to type 'false | undefined'.
Type 'true' is not assignable to type 'false'.

Solution: be sure to define your props as not being a multiselect element. ie:

  • not selectProps: Props<BookType>
  • but selectProps: Props<BookType, false>





Discover More
How to create a Select element in React?

This page is the creation of a HTML select element in React and how to handle it in a form In a non-controlled fashion, you need to read the value from the HTML select DOM element. form implementing...



Share this page:
Follow us:
Task Runner