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

Implement a Fallback Avatar URL

Refactor <Avatar /> props to be optional and then implement a fallback URL for your <Avatar /> component which will render when a url is not passed in. You’ll also use a fallback alt text.

Add this new test to Avatar.test.tsx:

it("should use a fallback image if no URL passed in", () => {
    render(<Avatar />);

    const img = screen.getByAltText(FALLBACK_AVATAR_ALT_TEXT);
    expect(img).toHaveAttribute("src", FALLBACK_AVATAR_URL);

Run yarn test and our test should fail. We need both of these values defined so define them inside Avatar.tsx.

You’ll see it’s still failing. Let’s make it pass.

Use these as default values for your props. Now we can either mark them as required props or we can leave as is. But our test is passing.


Inside Avatar.test.tsx add a new test. In this test, Avatars use a fallback image if no URL is passed in. Open your terminal and run yarn test. A couple of things to point out here. First, the test is failing. Second, we're getting some errors that we need to fix first.

We haven't defined this. We haven't defined this. Also, Avatar is missing those props. When you hover over, you'll see Type, empty object is missing the following properties from type AvatarProps. It tells you URL and ALT. Very helpful.

Let's fix these. I'm going to copy this, and copy this. Now I'm going to open up Avatar.tsx. I'm going to hide the terminal for now. What we're going to do is add a question mark here and make these optional. Now that they're optional, we want to add some default fallback values.

Here, our URL is going to be FALLBACK URL and ALT is going to be ALT Text. Now we'll go to the top of the file, and we'll write const, and we'll do the URL first. For that, we will go back and use this for now.

Then second, we'll do the alt text, which will be @, and we'll do hello-cat. We'll add some space. Now, if you go back to Avatar.test.tsx, we no longer have the red squiggly for our Avatar component.

We do have these. That's because we need to import them. To import them, we need to export them. We'll add the export keyword before both of these, save. I'll add both of these here. Just like that.

Now if we come back to the bottom, we open up our terminal. We'll restart Vitest. We'll see that now everything is passing. Great.