Skip to content

Instantly share code, notes, and snippets.

@azamatsmith
Created December 13, 2018 23:14
Show Gist options
  • Select an option

  • Save azamatsmith/8fef677fc0defcdd00a17f160687cad3 to your computer and use it in GitHub Desktop.

Select an option

Save azamatsmith/8fef677fc0defcdd00a17f160687cad3 to your computer and use it in GitHub Desktop.
Gatsby - Reusable Static Query Example
import React from 'react';
import PropTypes from 'prop-types';
import { graphql, StaticQuery } from 'gatsby';
function TestimonialQuery({ children, identifier }) {
return (
<StaticQuery
query={graphql`
query {
allContentfulTestimonial {
edges {
node {
identifier
image {
title
fluid(maxWidth: 437) {
...GatsbyContentfulFluid_withWebp
}
}
}
}
}
}
`}
render={({ allContentfulTestimonial }) =>
children(
allContentfulTestimonial.edges.find(
({ node }) => node.identifier === identifier,
),
)
}
/>
);
}
TestimonialQuery.propTypes = {
children: PropTypes.func.isRequired,
identifier: PropTypes.string.isRequired,
};
export default React.memo(TestimonialQuery);
@silencej
Copy link
Copy Markdown

Smart trick. But why is it not mentioned in the official Gatsby document?

@azamatsmith
Copy link
Copy Markdown
Author

Whoa, I forgot about this one. There is a downside to this but I can't remember what it is. I think it ends up adding all of the allContentfulTestimonial items into the browser but for my use case, it wasn't a big deal.

@silencej
Copy link
Copy Markdown

Better to use hooks. Hooks are reusable.

@azamatsmith
Copy link
Copy Markdown
Author

Yeah, this was created before hooks existed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment