Skip to main content

Joel M. Turner

Create an Avatar Component in Gatsby with TypeScript Part 1

This is part 1 of the Create an Avatar Component in Gatsby with TypeScript series

  1. 1) Create an Avatar Component in Gatsby with TypeScript Part 1
  2. 2) Create an Avatar Component in Gatsby with TypeScript Part 2: Gatsby Image
  3. 3) Create an Avatar Component in Gatsby with TypeScript Part 3: Adding Types

In this series we're going to take a look at creating a simple avatar component that is typed with TypeScript and has some special goodies in Gatsby land.

I usually write TypeScript from the start, but I wanted to show each piece individually in case others aren't familiar with TypeScript yet.

Let's start by identifying what our needs are for our avatar component.

  • Should show an image
  • Should be round
  • Should accept an image url
  • Should display an image based on a name (for small sets)

Cool, now we can start building our avatar. Start with an img element using a placeholder image as src. Add a little bit of styling to make it round and give it a size.

1function Avatar(props) {
2 const { url, altText, title } = props;
3
4 const styles = {
5 width: "75px",
6 height: "75px",
7 borderRadius: "50%",
8 };
9
10 return <img style={styles} src={url} alt={altText} title={title} />;
11}
12
13export default Avatar;

Then we can pass it the image url and alt text. We can see that the component is working in its basic implementation now.

1<Avatar
2 url="https://res.cloudinary.com/joelmturner/monster-01.png"
3 alText="Monster P. Whittington portrait"
4 title="Monster P. Whittington"
5/>
  • Should show an image
  • Should be round
  • Should accept an image url
  • Should display an image based on a name (for small sets)

Looks good. We've met our first three criteria for this component. In step 2 we'll make it more powerful with Gatsby Image.

Category
dev
Tags:
React
Discuss this article on Twitter

© 2012-2020, Proudly built with Gatsby and Theme UI