Working with External Libraries 5 exercises

React-Select's Generics

React Select is a popular library for building select components, but many developers face difficulties in creating their own abstraction from it.

Consider this Select component and array of guitarists:

export const Select = (props) => {
return <ReactSelect {...props} />;

Loading exercise


00:00 In this exercise, we're going to look at a classic integration problem between React and TypeScript, which is React Select. React Select is a really popular library for building select components. And I've noticed actually in a couple of production code bases I've looked at, they use this and they have a real problem wrapping it and creating their own abstraction from it.

00:19 So what we're going to look at here is we're trying to create a select component and we're returning React Select. And we're just basically trying to figure out the type for this props type. Because React Select itself, what we'll see is that it actually contains a few generics here.

00:36 And in order to get it working, we want to really mimic those generics on our select component. Now, what it's supposed to be doing is we're taking in some guitarists here. And these guitarists, we've got an ID and a label on them, Jimmy and Stevie Ray. And if we take a look at this select here,

00:55 we should see that on change, this option is supposed to be typed as option or null here. Because technically, you can select no guitarists or you can select one guitarist. But if we choose the isMulti option,

01:11 then this instead of being just like whenever you change it has a single option, this should instead be an array of options because you can select multiple guitarists. So this is a bit of a problem. And select or React Select itself handles this if you just use the component itself.

01:29 Because if we were to just change this to React Select, then it actually just starts working. We've got like a single value option or we've got a multi-value option. And your job is to try to get that same inference working on our little select component. So you should dive into React Select itself.

01:48 You should also take a look at a type called props, which React Select exports. And I think you have all the information you need. Good luck. This is a tough one.