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

Use in “Production” CodeSandbox

Copy your component into a StackBlitz using the React/TypeScript template and test it in a “production” setting.

After signing into CodeSandbox, select Create → React/TypeScript.

Create a new file called Avatar.tsx and copy your component into it.

import { useState } from "react"

export const FALLBACK_AVATAR_URL = "https://cataas.com/cat/says/hello%20world!"
export const FALLBACK_AVATAR_ALT_TEXT = "@hello-cat"

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;

function Avatar({url = FALLBACK_AVATAR_URL, alt = FALLBACK_AVATAR_ALT_TEXT}: AvatarProps) {
    const [srcToRender, setSrcToRender] = useState(url)
    return <img src={srcToRender} alt={alt} onError={() => setSrcToRender(FALLBACK_AVATAR_URL)}/>

export default Avatar

Import inside App.tsx and add to render block without props. Make sure it works. Test no URL, bad URL, real URL, and find an image online


The following resources provide more information for this lesson:


After signing in to CodeSandbox, head over to the top right and click, "Create." Select React Typescript, and this will create a new project using React and Typescript as the template. Inside the source directory, create a new file called Avatar.tsx. Head back over to your IDE, select all from Avatar.tsx and copy it.

Head back to CodeSandbox, paste it in, and hit, "Save." Now, go into app.tsx and import your component. Then, add it and for the first iteration, just add it without any props. Click, "Save." We'll hide this on the left.

As you can see, it's working. It loads our fallback image. If we go ahead and inspect, we'll see that the alt is being used as well. Now, I'm going to search for just a random picture. I'm going to look for the Mandalorian.

I'm going to copy that image address. Go onto my Avatar, and for URL, I'm going to paste that in. I'm going to refresh the page, and you'll see that it uses our Mandalorian image. It's working. That's awesome. Now, last thing I'll do is just open up this URL in its own tab.

As you can see, we're now using our avatar component in a production setting. You could send this to whoever you want and now you can say that you've written React in Typescript components and deployed them to production. Nice work.