'Gatsby Image query returns out of order images
I'm making a Gatsby Image gallery with 650 images.
Images are named sequentially: 1.jpg, 2.jpg, 3.jpg, ..., 650.jpg
Then I run this query, which should order them by name:
export const query = graphql`
query ImagesForGallery {
images: allFile(filter: { relativeDirectory: { eq: "gallery" } }, sort: { fields: name }) {
edges {
node {
childImageSharp {
thumb: fluid(maxWidth: 270, maxHeight: 270) {
...GatsbyImageSharpFluid
originalName
}
full: fluid(maxWidth: 1024) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
Then, pictures are returned in this order:1.jpg, 10.jpg, 100.jpg, 101.jpg, ..., 2.jpg, 20.jpg, 200.jpg, 201.jpg, ...
So, the images are not being returned in numeric order, but they are using some sort of pseudo-alphabetical order instead. :(
How can I return them in numeric order OR, how can I rename all images to comply with Gatsby order ?
Edit: The easiest way to test is with 6 pictures named:1.jpg, 2.jpg, 10.jpg, 11.jpg, 100.jpg, 101.jpg
Solution 1:[1]
i don't think you can do it in gatsby query directly, beceause it's kind of specific.
What you could do, is handle it with javascript after you got the data. I've made some code that handle the job
var points = ['1.jpg', '32.jpg', '210.jpg', '11.jpg', '1020.jpg', '101.jpg'];
points.sort((a, b) => split(a) - split(b));
const split = (strNumber) => strNumber.split('.')[0]
// will give
["1.jpg", "11.jpg", "32.jpg", "101.jpg", "210.jpg", "1020.jpg"]
Let me know if it works
Solution 2:[2]
Your almost there, the query sort
attribute looks to be off.
playing with it in the grapqhl playground i was able to sort using base
{
allFile(sort: { fields: [base] }) {
edges {
node {
base
childImageSharp {
fluid {
src
}
}
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | DarioRega |
Solution 2 | Aereli |