Skip to content

Instantly share code, notes, and snippets.

@pqt pqt/DynamicImage.jsx Secret
Last active Apr 22, 2019

Embed
What would you like to do?
import * as React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
function renderImage(file) {
return (
<Img fluid={file.node.childImageSharp.fluid} />
);
}
export default function DynamicImage({ image }) {
const images = useStaticQuery(graphql`
{
allFile(
filter: {
dir: { regex: "/src/images/" }
extension: { regex: "/jpeg|jpg|png|gif/" }
}
) {
edges {
node {
extension
relativePath
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`);
return renderImage(
images.allFile.edges.find((file) => file.node.relativePath === image)
);
}
const images = useStaticQuery(graphql`
{
allFile(
filter: {
dir: { regex: "/src/images/" }
extension: { regex: "/jpeg|jpg|png|gif/" }
}
) {
edges {
node {
extension
relativePath
childImageSharp {
fluid(maxWidth: 1920) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`);
function renderImage(file) {
return (
<Img fluid={file.node.childImageSharp.fluid} />
);
}
export default function DynamicImage({ image }) {
// ...
return renderImage(
images.allFile.edges.find((file) => file.node.relativePath === image)
);
}
import React from 'react';
import { graphql, useStaticQuery } from 'gatsby';
import Img from 'gatsby-image';
export default function StaticImage() {
const data = useStaticQuery(graphql`
query {
file(relativePath: { eq: "avatars/austin-paquette.jpeg" }) {
childImageSharp {
# Specify the image processing specifications right in the query.
# Makes it trivial to update as your page's design changes.
fixed(width: 125, height: 125) {
...GatsbyImageSharpFixed
}
}
}
}
`);
return <Img fixed={data.file.childImageSharp.fixed} />;
}
import React from 'react';
import DynamicImage from '../path/to/your/components';
export default function Usage() {
return <DynamicImage image="image_name.jpg" />;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.