In Part 1 we put together a simple avatar component that can receive an image url and render it out as a round image.
To get the full benefit of Gatsby Image we need to make sure our image is pulled into our graphql. We'll need to install a couple of plugins to help us here.
gatsby-plugin-sharp will be needed.
Then, if you don't already have
gatsby-plugin-sharp we can install them.
Then in your gatsby-config.js:
We'll need a source plugin set up as well. For this example we're going to use
gatsby-source-filesystem. Here what our
gatsby-config might look like, assuming our images are in
Now let's drop our image file into our assets folder and create a query for it. We can use the hook for StaticQuery in our component which will make the image available through the data prop. Since we know the size of the image we can add those dimensions in our graphql query so the so the browser doesn't have to do all the work.
Then we need to add the
Img component from
gatsby-image so that it can do its magic.
Now let's put it all together.
We're still missing the ability to pass a url to our avatar component so let's add that back in. We can return a regular
img element if we get a url. Using
fixed will be better since we're not worried about fluid mode with this component.
This allows us to call avatar without us needing to pass a prop of image url. If you need multiple avatar images for your team you can add them to the quite and pass a user prop down and we'll grab that from the query. We can name the queries to match the users like so:
That way we can pass
monster2 in our
user prop to have it render that monster.
Nice, now we can type it so it's easier to know what name can be used and to see if our structure is correct if we ever need to edit it.