Skip to content

Instantly share code, notes, and snippets.

@meritozh
Created January 11, 2019 11:51
Show Gist options
  • Select an option

  • Save meritozh/d36408e50e96b85d17d879b6e2a0334f to your computer and use it in GitHub Desktop.

Select an option

Save meritozh/d36408e50e96b85d17d879b6e2a0334f to your computer and use it in GitHub Desktop.

Revisions

  1. meritozh created this gist Jan 11, 2019.
    89 changes: 89 additions & 0 deletions Image.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,89 @@
    /*
    * This component is built using `gatsby-image` to automatically serve optimized
    * images with lazy loading and reduced file sizes. The image is loaded using a
    * `StaticQuery`, which allows us to load the image from directly within this
    * component, rather than having to pass the image data down from pages.
    *
    * For more information, see the docs:
    * - `gatsby-image`: https://gatsby.app/gatsby-image
    * - `StaticQuery`: https://gatsby.app/staticquery
    */

    import React from 'react'
    import { StaticQuery, graphql } from 'gatsby'
    import Img from 'gatsby-image'
    import styled from 'styled-components'
    import R from 'ramda'

    interface DataType {
    allFile: AllFileType
    }

    interface AllFileType {
    edges: EdgesType[]
    }

    interface EdgesType {
    node: NodeType
    }

    interface NodeType {
    childImageSharp: FluidType
    relativePath: string
    name: string
    }

    interface FluidType {
    fluid: any;
    }

    type AdditionalImageProps = {
    maxWidth?: string
    src?: string
    }

    type ChangedImageProps = Record<
    Exclude<keyof AdditionalImageProps, 'src'>,
    string
    >

    const StyledDiv = styled.div.attrs<AdditionalImageProps, ChangedImageProps>({
    maxWidth: props => props.maxWidth || `320px`,
    })`
    max-width: ${props => props.maxWidth};
    `

    const Image: React.FunctionComponent<AdditionalImageProps> = props => (
    <StaticQuery
    query={graphql`
    query {
    allFile(filter: { extension: { eq: "png" } }) {
    edges {
    node {
    relativePath
    name
    childImageSharp {
    fluid {
    ...GatsbyImageSharpFluid
    }
    }
    }
    }
    }
    }
    `}
    render={(data: DataType) => {
    const index = R.findIndex(
    R.includes(props.src),
    R.map((n: EdgesType) => n.node.relativePath)(data.allFile.edges)
    )
    const image = data.allFile.edges[index];

    return <StyledDiv {...props}>
    <Img fluid={image.node.childImageSharp.fluid} />
    </StyledDiv>
    }}
    />
    )

    export default Image