Created
August 3, 2019 00:31
-
-
Save chrispian/b414dd88a93e2fe9fa778f109b313d1f to your computer and use it in GitHub Desktop.
Gatsby + WordPress TypeError: Cannot read property 'source_url' of null
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import { Link, graphql } from "gatsby" | |
import Img from "gatsby-image" | |
import Layout from "../components/layout" | |
import SEO from "../components/seo" | |
export default ({ data }) => { | |
return ( | |
<Layout> | |
<SEO title="home" /> | |
{data.allWordpressPost.edges.map(({ node }) => ( | |
<div> | |
<Link to={node.slug}> | |
<p>{node.title}</p> | |
</Link> | |
/* This throws an error: TypeError: Cannot read property 'source_url' of null */ | |
/* I've tried several ways of doing this, always throws that error. */ | |
<img src="{node.featured_media.source_url}" border="0" alt="{node.title}" /> | |
/* console.log shows the correct value, the URL of the image I want to use. */ | |
{console.log(node.featured_media.source_url)} | |
<div | |
/* Remove the read more link from the WP Excerpt. It links back to the original url instead of local Gatsby. */ | |
dangerouslySetInnerHTML={{ | |
__html: node.excerpt.replace(/<a class="more-link.*/, ''), | |
}} | |
/> | |
</div> | |
))} | |
</Layout> | |
) | |
} | |
export const pageQuery = graphql` | |
query { | |
allWordpressPost(sort: {order: DESC, fields: [date]}) { | |
edges { | |
node { | |
title | |
excerpt | |
slug | |
featured_media { | |
source_url | |
} | |
} | |
} | |
} | |
} | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's the console.log errors: