Created
December 13, 2018 23:14
-
-
Save azamatsmith/8fef677fc0defcdd00a17f160687cad3 to your computer and use it in GitHub Desktop.
Gatsby - Reusable Static Query Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
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.
Better to use hooks. Hooks are reusable.
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
Smart trick. But why is it not mentioned in the official Gatsby document?