Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot read property 'childImageSharp' of null #2567

Closed
cryptoverted opened this issue Oct 21, 2017 · 31 comments
Closed

Cannot read property 'childImageSharp' of null #2567

cryptoverted opened this issue Oct 21, 2017 · 31 comments

Comments

@cryptoverted
Copy link

cryptoverted commented Oct 21, 2017

I've been playing with Gatsby trying to create a website that pulls data from a json file and generates pages. On each page a list of links/cards is displayed. Everything worked fine until I added images and tried using the sharp plugin (gatsby-plugin-sharp and gatsby-transformer-sharp)

If I remove from the card.js file, image from the Card_details fragment, const { small } = image.childImageSharp, and the img tag, it all works as expected except no image.

This error in GraphiQL

{
  "errors": [
    {
      "message": "Path must be a string. Received undefined",
      "locations": [
        {
          "line": 9,
          "column": 7
        }
      ],
      "path": [
        "linksJson",
        "links",
        0,
        "image"
      ]
    }
  ],
  "data": {
    "linksJson": {
      "page": "/page1",
      "title": "Page 1",
      "links": [
        {
          "title": "Card 1",
          "url": "https://www.gatsbyjs.org/tutorial/",
          "description": "Card 1 description.",
          "image": null
        }
      ]
    }
  }
}

and this in the chrome console

card.js:19 Uncaught TypeError: Cannot read property 'childImageSharp' of null
at Card.render (card.js:19)
at Card.render (createPrototypeProxy.js:44)
at ReactCompositeComponent.js:793
at measureLifeCyclePerf (ReactCompositeComponent.js:73)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:792)
at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:819)
at ReactCompositeComponentWrapper.performInitialMount (ReactCompositeComponent.js:359)
at ReactCompositeComponentWrapper.mountComponent (ReactCompositeComponent.js:255)
at Object.mountComponent (ReactReconciler.js:43)
at ReactDOMComponent.mountChildren (ReactMultiChild.js:234)

Am I missing something or doing something wrong? The index page generates correctly and displays a list of pages, when I click to one of the pages, that is when it doesn't work. Thanks for any help.

Here is the code I use.

links.json

[
  {
    "page": "/page1",
    "title": "Page 1",
    "links": [
      {
        "title": "Card 1",
        "url": "https://www.gatsbyjs.org/tutorial/",
        "description": "Card 1 description.",
        "image": "images/2015-03-02-11.30.09.jpg"
      }
    ]
  },
  {
    "page": "/page2",
    "title": "Page 2",
    "links": [
      {
        "title": "Card 1",
        "url": "https://www.gatsbyjs.org/tutorial/",
        "description": "Card 1 description.",
        "image": "images/2015-06-20-11.09.16.jpg"
      },
      {
        "title": "Card 2",
        "url": "https://www.gatsbyjs.org/tutorial/",
        "description": "Card 2 description.",
        "image": "images/2015-12-07-20.31.40.jpg"
      }
    ]
  }
]

page.js template

import React from 'react';
import Helmet from 'react-helmet';
import Card from "../components/card"

export default function Template({data}) {
  const {linksJson: pages} = data;
  return (
    <div>
    <h2>{pages.title}</h2>
    <ul>
    {pages.links.map((node, key) => (
    <li key={key}>
    <Card
    
    card={node}
    />
</li>
    ))}
    </ul>
    </div>
  )
};

export const pageQuery = graphql`
  query PageByPath($path: String!) {
    linksJson (page: {eq :$path}) {
      page
      title
      ...Card_details
    }
  }
`

card.js component

import * as PropTypes from "prop-types"
import React from "react"
import Link from "gatsby-link"
import styles from '../layouts/card.module.scss';

class Card extends React.Component {
  static propTypes = {
    card: PropTypes.shape({
      title: PropTypes.string.isRequired,
      url: PropTypes.string.isRequired,
      description: PropTypes.string.isRequired,
      image: PropTypes.object,
    }).isRequired,
  }
  constructor() {
    super()
  }

  render() {
    const { title, url, description, image } = this.props.card
    const { small } = image.childImageSharp

    return (
      <a
        href={url}
        className={styles.card}
      >
 
        <img
          src={small.src}
          srcSet={small.srcSet}
          sizes="(min-width: 960px) 292px, 33vw" 
          className={styles.image} 
          alt="" 
        />

        <div className={styles.content}>
          <h2 className={styles.title}>
            {title}
          </h2>
          <p className={styles.description}>
            {description}
          </p>
        </div>

      </a>
    )
  }
}

export default Card

export const CardFragment = graphql`
  fragment Card_details on LinksJson {
    links {
      title
      url
      description
      image {
        childImageSharp {
          small: responsiveSizes(maxWidth: 292, maxHeight: 292) {
            src
            srcSet
          }
        }
      }
    }
  }
`
@adamwiggall
Copy link

I've had this error and for me, the path for the image was the issue.

Do get the same result if you change the path for an image from
"images/2015-12-07-20.31.40.jpg"
to
"./images/2015-12-07-20.31.40.jpg" ?

@cryptoverted
Copy link
Author

@adamwiggall I tried that but I get the same errors

@adamwiggall
Copy link

@cryptoverted then I'm all out of ideas. I did have times where I had to restart the development server for a revised path to 'catch'.

@cryptoverted
Copy link
Author

@adamwiggall I've tried that too

@KyleAMathews
Copy link
Contributor

@cryptoverted have you tried one of example sites that use gatsby-transformer-sharp? image-processing + using-gatsby-image are great examples of how to do things.

@LekoArts
Copy link
Contributor

@cryptoverted Did you try deleting the .cache and public folder and then running the dev server again?

@theutz
Copy link

theutz commented Oct 25, 2017

I'm having the same issues using the YAML transformer plugin, too.

@cryptoverted
Copy link
Author

@KyleAMathews I've looked at that example but I mostly followed gatsbygram
@LekoArts I've tried deleting the .cache, still nothing

@KyleAMathews
Copy link
Contributor

Deleting the cache rarely helps.

Try installing and running an example site to see if they work for you? Perhaps it's something wrong on your OS.

@theutz
Copy link

theutz commented Oct 26, 2017

Just to shed some light on my angle with the problem, it seemed to occur most when I was referencing images in a yaml (or toml) file that were not at the root node. An example might help clarify:

Works Fine

image: "./hero-bg.jpg"

When I reference a file in the same directory as my yaml/toml file, the paths appear to be queryable as ImageSharp objects through both GraphiQL and Gatsby. However, if I simply nest the path reference like this:

Gives the same error mentioned in the thread

image:
  src: "./hero-bg.jpg"

I hope this helps clarify what might be going on!

@KyleAMathews
Copy link
Contributor

@theutz have you tried upgrading? This is a bug that was fixed fairly recently.

@theutz
Copy link

theutz commented Oct 26, 2017

@KyleAMathews I hadn't, but I just upgraded everything and still got the bug. For reference, I'm running the following:

The Packages

  • gatsby@1.9.80
  • gatsby-plugin-sharp@1.6.12
  • gatsby-source-filesystem@1.5.5
  • gatsby-transformer-sharp@1.6.13
  • gatsby-transformer-yaml@1.5.11

The Query

{
  allHomeYaml {
    edges {
      node {
        title
        splash {
          src {
            id
          }
        }
      }
    }
  }
}

The YAML

title: Everyone has the ability to recover from addiction and mental health issues
body: ....
splash: 
  src: ./hero-bg.jpg

The Output from GraphiQL

{
  "errors": [
    {
      "message": "Path must be a string. Received undefined",
      "locations": [
        {
          "line": 7,
          "column": 11
        }
      ],
      "path": [
        "allHomeYaml",
        "edges",
        0,
        "node",
        "splash",
        "src"
      ]
    }
  ],
  "data": {
    "allHomeYaml": {
      "edges": [
        {
          "node": {
            "title": "Everyone has the ability to recover from addiction and mental health issues",
            "splash": {
              "src": null
            }
          }
        }
      ]
    }
  }
}
@KyleAMathews
Copy link
Contributor

Hmmm sounds like a bug then. Would love it if you wanted to try narrowing down the source. Failing that, the most helpful thing to do is build a reproduction site to let me or another maintainer debug what's wrong.

@theutz
Copy link

theutz commented Oct 26, 2017

@KyleAMathews We do our dev on BitBucket, but I pushed the branch we're having this problem on to a new Github repo for your perusal. Thanks!

https://github.com/theutz/skywood-gatsby-bug

@KyleAMathews
Copy link
Contributor

So tried running it locally and… it worked fine on my machine :-) Pretty site btw!

@theutz
Copy link

theutz commented Oct 26, 2017

Thanks! And thanks for looking! I'll keep trying to figure out what's going on over here! :)

@cryptoverted
Copy link
Author

I tested both skywood and image-processing on my computer and they both work. At this point I think I am making a mistake somewhere?
I've uploaded the code here: https://github.com/cryptoverted/test-bug

@KyleAMathews
Copy link
Contributor

KyleAMathews commented Oct 27, 2017

@cryptoverted thanks for the repo!! That helped me figure out what was going on. We'd been fixing this for markdown frontmatter but your reproduction helped me realize we should just do this for all nodes.

PR @ #2654

@cryptoverted
Copy link
Author

@KyleAMathews Thanks! All working now

@ghost
Copy link

ghost commented Mar 19, 2019

@cryptoverted Did you try deleting the .cache and public folder and then running the dev server again?

Thanks to you solved my problem.
It was caused by cache.

@keithmifsud
Copy link

Just a note for future readers: I had this problem after renaming a directory of a blog post. Running gatsby clean worked for me straight away.

@ahojukka5
Copy link

A note for everyone coming to this thread by googling. After gatsby new, you might have in your gatsby-config.js something similar like this:

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },

After you start implementing blog posts like in the tutorial, you might add or change the code following:

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },

Now, you might have something like this:

  const data = useStaticQuery(graphql`
    query {
      headerImage: file(relativePath: { eq: "header.jpg" }) { // <--- here
        childImageSharp {
          fluid(maxWidth: 1200) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)

Then you have error Cannot read property 'childImageSharp' of null. The reason is that the relative path has changed. It's now images/header.jpg.

@manuelojeda
Copy link

For some reason, when you do the first gatsby build it will break at childImageSharp, but if you run again gatsby build it will work perfectly.

You can do a double gatsby build and it will works fine.

@myerzman
Copy link

For some reason, when you do the first gatsby build it will break at childImageSharp, but if you run again gatsby build it will work perfectly.

You can do a double gatsby build and it will works fine.

Double build worked for me as well...

@JapaneseMayonnaise
Copy link

@cryptoverted Did you try deleting the .cache and public folder and then running the dev server again?

Thanks so much for this! After trying pretty much everything I could find on the internet, only this worked like magic. But, why does this solve the issue?

@rishFilet
Copy link

A note for everyone coming to this thread by googling. After gatsby new, you might have in your gatsby-config.js something similar like this:

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },

After you start implementing blog posts like in the tutorial, you might add or change the code following:

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },

Now, you might have something like this:

  const data = useStaticQuery(graphql`
    query {
      headerImage: file(relativePath: { eq: "header.jpg" }) { // <--- here
        childImageSharp {
          fluid(maxWidth: 1200) {
            ...GatsbyImageSharpFluid
          }
        }
      }
    }
  `)

Then you have error Cannot read property 'childImageSharp' of null. The reason is that the relative path has changed. It's now images/header.jpg.

This fixed the issue for me, many thanks!

@karen-ka
Copy link

I had this issue and tried the methods mentioned above, to no avail. What ended up working mysteriously was just renaming the directory containing the img coming up as null (and updating all references), and that fixed the error.

@DhiraNegi
Copy link

i tried everything mentioned above. Nothing works for me. Please help.

@keithmifsud
Copy link

@DhiraNegi ... I've started getting this issue again on a new site using a pre-built theme. The solution was to stop the dev server, delete the .cache directory and re-run the server. I assume that gatsby clean will also work.

The issue happens when you update assets queried through GraphQL while the server is running.

@noctemjs
Copy link

In my case, I'm working with an MDX blog and what solved it was to specify the image on the MDX file. And don't forget to have an image on every folder.

Before:

title: Third Post!
date: 2020-09-10
published: true

After

title: Third Post!
date: 2020-09-10
published: true
image: ./landscape.jpg

@phxwh
Copy link

phxwh commented Jun 27, 2021

I found out that I got this error because I missed the img Alt information in the .MD file I have
Before:
img: ../../static/images/image1.jpeg
After (worked)
img: ../../static/images/image1.jpeg
imgAlt: description of image1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet