Understanding React's ElementType and ComponentType
The ElementType
and ComponentType
type helpers show up often when working with React.
type types = [React.ElementType, React.ComponentType];
React.ElementType
The ElementType
type helper is a bit unusual because it accepts some props and derives what types of componen
Transcript
00:00 Let's take a look at two more type helpers that crop up again and again and again when you're using React. We have element type and component type here. Now element type is really weird because what it does is it basically accepts kind of some props here. And it kind of derives what types of components
00:18 would be able to be like, receive those props. So here we have example, we can see that it takes in an audio or video or a React.component type of autoplay. And that's because we've got autoplay inside here. If we, for instance, just did like a blah, blah, blah, blah,
00:39 like this, and we made it required, then we'd see that the only thing that could possibly fulfill this, we can't actually use like audio or video here. We can only have a custom component that's passed to this slot. So element type basically corresponds to any custom component that you can think of,
00:56 but also anything like div, span, or things like that that can receive these props. So for instance, if we have a href and we make it like this and a string, so optional string, then this loads of stuff can accept a href, right? So symbol, a, area, base, link, SVG, animate,
01:14 all this stuff can accept a href. So React element type, basically it's kind of like React component type, which we'll see in a second, but it can also kind of like be relied on to fetch all of these different stuff from JSX.IntrinsicElements itself. So now let's take a look at component type itself.
01:34 Component type, down here, we've basically got an array of React.ComponentTypes, and if I just indent this, you'll be able to see this a little bit clearer. Here we've got React.ComponentType, which takes in a certain prop, and that prop is prop one, it's required, and it's a string. We've got a functional component that takes in that
01:52 and a class component that takes in that too. And we're kind of just putting them down here inside this array so we can see it all working. If we change this one to prop two here, you'll see the class component actually starts erroring because prop one is not assignable to prop two string. And that's kind of interesting. So this means then that we can use component type
02:11 to basically represent either functional components or class components. And they're useful because if we pass them into like higher order components or things like this, we probably want to be using component type here. But element type does have its uses too because it means that you can actually pass in kind of any element whatsoever along with class components. And that's going to be really cool
02:31 when we approach the as prop, for instance, too.