Reputation: 5
I want to list all wordpress posts on my gatsby.js page, and to filter them by category when the user clicks on category-tab. When the category is selected, I save it as "choosenCategory"variable and it is a string. I have a problem finding a way to pass a variable to my query and this approach doesn't work:
const chosenCategory = "myCategory";
const PostListingData = (props) => (
<StaticQuery
query={graphql`
query($name: String = chosenCategory) {
allWordpressPost(filter:
{ categories:
{ elemMatch:
{ name:
{ eq:
$name
}
}
}
}
)
{
edges {
node {
id
title
categories {
name
}
}
}
}
}
`}
render={data => <PostsListing data={data} {...props} />}
/>
)
const PostsListing = ({ data }) => {
return (
<div>
{data.allWordpressPost.edges.map(({ node }, i) => (
*** some code ***
))}
</div>
)}
Upvotes: 0
Views: 2259
Reputation: 123
Just to clarify, the reason this won't work is that Gatsby has no way to generate a site that dynamically loads content based on a variable set at runtime. If it did accept the code you wrote, it would only be able to generate one category "myCategory". Instead of doing that, Gatsby just rejects variables in the queries.
In my experience, there are a few options:
Generate a page for every category using gatsby-node.js. https://www.gatsbyjs.org/tutorial/part-seven/
Use a search plug-in. Essentially this option is generating a tree based off of all the posts and putting that on the page that the search shows up on.
Make your own search. This is similar to #2. You will have to bring in ALL posts, make components for all of them, and then set them to visible based off of the search component's state.
Upvotes: 1