Components 7 exercises

Add HTML Props to React Components

Here's the code we started with:

export const Button = ({ className, }: {}) => {
return (
<button {} className={`default-classname ${className}`}></button>

The first thing we can do is hover over button to see its type definition:


Loading solution


0:00 Let's take a look at this. The way that we know that we can extract out or understand the types of these props is by looking at this button. What we've got here is a really, really long type definition here.

0:13 We can copy and paste this over. Let's have a look at this. We can stick all of that up there. This is going to work React.DetailedHTMLProps, React.ButtonHTMLElements, HTMLButtonElement, HTMLButtonElement. There's a lot going on there.

0:32 We've got our Button here. Now, we're going to get autocomplete on all of these properties. We've got button, reset, and submit in the type. We can pass it at access key, all of this stuff, and this is behaving like a regular button.

0:46 This is good, but why do we need all of this stuff here? React.DetailedHTMLProps is not really adding anything up here? It's adding a ref, I guess, but we can remove this wrapper here and we just end up with React.ButtonHTMLAttributes, HTMLButtonElements.

1:08 Still extremely verbose here. Wouldn't it be nice if we had a helper type that could help us out here? We can still pass everything that we need to inside here. Can we pass it a ref? I'm not sure we can. That's right, because we're not using forward ref or anything.

1:26 What's the actual best way to solve this? Well, it's with a type helper and that type helper is ComponentProps. Now, ComponentProps is available on React itself, but you can also import it separately. We can either do React.ComponentProps or just import ComponentProps.

1:42 What we do with ComponentProps is we can pass it a native type here, one of these native things, and we can grab all of the props from it. If we try to do it with the wrong thing, if we try to say ComponentProps, "div," then button is going to yell at us like, "Whoa, that's a big old type error."

2:00 Essentially, property 'align' is missing in 'HTMLbuttonElement', but required in 'HTMLDivElement'. You can see what's going wrong there. Of course, type button is not available on it either. ComponentProps, "button" lets you extract out beautifully the native types from these HTML elements. This is the canonically best way to do it.