Build a Dynamic Avatar Component with React & TypeScript Tutorial (14 exercises)

Define AvatarProps

Refactor the <Avatar /> to take url and alt as props.

Inside, Avatar.test.tsx add the following test:

it("should render the url and alt passed in", () => {
    const url = "https://cataas.com/cat/says/hello%20world!";
    const alt = "a beautiful cat";
    render(<Avatar url={url} alt={alt} />);

    const img = screen.getByAltText(alt);
    expect(img).toHaveAttribute("src", url);

Now run yarn test , it will fail. Go inside Avatar.tsx and define AvatarProps like so:

type AvatarProps = {
	/** the url of an image to render for the Avatar. **/
  url: string;
  /** the alt text to use for the url image. **/
	alt: string;

And now use them in your Avatar here and here.

And now our test passes. Woohoo!


The following resources provide more information for this lesson:


Inside of Avatar.test.tsx, add a new test. This test should render the url and alt passed in. Now open your terminal and run yarn test. You'll see it fails. We also have a type error in our editor. Let's first fix the type error.

At the top of Avatar.tsx, add AvatarProps. Let's talk about this. Here, we're defining the props for our Avatar component using a type alias, or type for short. We defining two properties, url, which is required -- it's of type string -- and alt. You'll see this is a notation called TSDoc. It allows you to add documentation to your types.

Now we'll come in here. We'll destructure url and alt. Then, to the right, we'll add the colon with AvatarProps. Now we'll use them. src is going to be url. alt is going to be alt. We'll save. We'll go on back. Looks like vitest stopped. We'll start it up again, yarn test.

Now this test is passing, but now our previous test is failing. We actually need to pass this in. We're just going to do the same thing. We'll come up here. We'll use a different alt. We'll say, "@."

We'll make sure this fails, actually. We'll just do that. Then we'll say, "url = url," and "alt = alt." We'll save, scroll all the way down. We'll see it's still failing. If we look at the dom, we expected that to fail. We'll say, "handle." We'll save. Now it is passing.

What we'll do is actually just clean this up and pass in alt. It is still going to pass. One last thing, I cleaned up these tests suites to make this a little bit more clear. This says it should render an img. This says it should use the url and alt passed in.