Use generics in React to make dynamic and flexible components

You can use generics in React to make incredibly dynamic, flexible components. Here, I make a Table component with a generic 'items' type.

Discuss on Twitter

Transcript

You might be used to using generics with functions, but you can also use them with React components. Here, this Table component, it takes in an array of items, which have currently time to just ID String. Then it also takes a function to render the item, which says Item ID String.

Actually, what you want here is you want to be able to parse in any items. For that ID String to then propagate through to the renderItem here. We can do that. You can make a item here, which would be, lets say, tItem. You might be put off by the fact that inside this TSX file, this syntax actually isn't valid.

What you need to do instead is you need to turn this table into a function, which looks like this, and remove the arrow. Now, you're allowed to use it. Here, we probably need to make this generic as well, tItem. Let's add tItem up here.

We can take the ID String and just put tItem in there. Anything we put into here, name, Matt, for instance, will be propagated through to our item because it's generic. If we ever want to pass the generic manually and specify it, then we can pass it here. We can say, "ID equals a number," for instance.

This will array because it's not passing that. It's a funny syntax. Not a lot of people know about it. I stumbled on it by accident. Every time I use it, I think, "Wow, that's pretty cool."

More Tips