I am trying to use Gatsby image but getting Cannot read property 'childImageSharp' of null. I can't find where is the error. Topsection.js is a under Component. the image.jpg is inside of src/images/images.jpg . Still getting the error.
Topsection.js
const TopSection = () => {
const data = useStaticQuery(graphql`
{
featureimg: file(relativePath: { eq: "image.jpg" }) {
childImageSharp {
fluid(maxWidth: 60) {
...GatsbyImageSharpFluid
}
}
}
}
`);
return (
<>
<div className="first-post-thumbnail">
<a href="/best-keyboard-for-wow/">
<Image fluid={data.featureimg.childImageSharp.fluid} />
</a>
</div>
</>
);
};
export default TopSection;
35 | <div className="first-post-thumbnail">
36 | <a href="/best-keyboard-for-wow/">
37 |
> 38 | <Image fluid={data.featureimg.childImageSharp.fluid} />
| ^ 39 |
40 | </a>
41 | </div>
Config
/**
* Configure your Gatsby site with this file.
*
* See: https://www.gatsbyjs.com/docs/gatsby-config/
*/
module.exports = {
/* Your site config here */
siteMetadata: {
title: ``,
description: ``,
author: ``,
},
plugins: [
`gatsby-plugin-react-helmet`,
`gatsby-transformer-sharp`, `gatsby-plugin-sharp`,
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `${__dirname}/src/images`,
},
resolve: `gatsby-plugin-prefetch-google-fonts`,
options: {
fonts: [
{
family: `Poppins`,
variants: [`200`,`300`,`400`,`500`,`600`,`700`, `900`]
},
],
},
},
],
}
Editors Note January 29, 2024: The answer below should be considered obsolete due to the gatsby-image package being deprecated. Only proceed if you are maintaining code or need a historical reference.
If you are building new, see replacement package: https://www.gatsbyjs.com/plugins/gatsby-plugin-image/
Original answer below this line.
Assuming you've set your filesystem correctly and the image is available by GraphQL.
Try:
import Img from "gatsby-image"
// other imports
const TopSection = () => {
const data = useStaticQuery(graphql`
query {
featureimg: file(relativePath: { eq: "/images/image.jpg" }) {
childImageSharp {
fluid(maxWidth: 60) {
...GatsbyImageSharpFluid
}
}
}
}
`);
return <div className="first-post-thumbnail">
<a href="/best-keyboard-for-wow/">
<Img fluid={data.featureimg.childImageSharp.fluid} />
</a>
</div>;
};
export default TopSection;
The relativePath
field of a file node is relative to the directory you specified in gatsby-source-filesystem
.
I would suggest using <Link>
component instead of native <a>
(anchor) for internal navigation:
<Link to="/best-keyboard-for-wow/">
Check the query in the GraphQL playground (localhost:8000/___graphql
) to check the spelling and the results.