images on Gatsby.js site won't display on GitHub pages - reactjs

I am having trouble getting images to display on github pages. I am using a repository based page. I have added in a simple img tag with in the JSX and tried using the method described in the Gatsby documentation. I feel like I'm missing something obvious.
Here is the code
import React, { useContext } from 'react';
import AnchorLink from 'react-anchor-link-smooth-scroll';
import { ThemeContext } from 'providers/ThemeProvider';
import { Header } from 'components/theme';
import { Container, Button } from 'components/common';
import dev from 'assets/illustrations/dev.svg';
import { Wrapper, IntroWrapper, Details, Thumbnail } from './styles';
import { withPrefix } from 'gatsby'
import HeadShotPlaceHolder from 'assets/images/HeadShotPlaceHolder.jpeg'
export const Intro = () => {
const { theme } = useContext(ThemeContext);
console.log(HeadShotPlaceHolder)
return (
<Wrapper>
<Header />
<IntroWrapper as={Container}>
<Details theme={theme}>
{/* <h1>Hi There!</h1> */}
<h1>Pamela Welch</h1>
{/* <h4>I’m John and I’m a JAMStack engineer!</h4> */}
<h4>A proven professional with extensive experience in all facets of communication and marketing.</h4>
<Button as={AnchorLink} href="#contact">
Hire me
</Button>
</Details>
<Thumbnail>
{/* This is where the image tag giving me the problem is */}
<img src={ withPrefix(HeadShotPlaceHolder) } alt="I’m John and I’m a JAMStack engineer!" />
</Thumbnail>
</IntroWrapper>
</Wrapper>
);
};
and here is the result
Image Link Broken

Your code looks good, your image has its path prefixed. However, to make it effective you need to run the following snippet in the deploy command:
{
"scripts": {
"deploy": "gatsby build --prefix-paths && gh-pages -d public"
}
}
Note the --prefix-paths flag.
More information in How Gatsby Works in GitHub Pages.

Related

Default layout in Gatsby MDX V4

I have recently updated Gatsby from V3 to V4(latest one) and also updated the plugins below.
"#mdx-js/mdx": "^2.1.3",
"#mdx-js/react": "^2.1.3",
"gatsby-plugin-mdx": "^4.1.0",
"gatsby": "^4.21.1",
The code in
node-config.js -
{
resolve: `gatsby-plugin-mdx`,
options: {
defaultLayouts: { default: require.resolve(`./src/components/layout`), },
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages/`,
},
},
In /src/pages/index.mdx
---
title: Title
description: Description
class: home
imageTwitter: /twitter-home.jpg
imageOg: "/og-home.jpg"
imageAlt: Image for the Title.
---
import { StaticImage } from "gatsby-plugin-image"
import { Container, Row, Col, Card } from "react-bootstrap"
import { Link } from "gatsby"
import { navigate } from "gatsby"
<div class="w-60 text-center home-intro">
content
</div>
Latest version of gatsby-plugin-mdx doesn't have defaultLayout so when I hit http://localhost:8000/ the page loads without header and footer because the layout doesn't work.
In /src/components/layout.js
import React from "react"
import PropTypes from "prop-types"
import { StaticQuery, graphql } from "gatsby"
import { Container, Row, Col } from "react-bootstrap"
import "../styles.scss"
import Footer from "./footer"
import Menu from "./menu"
import Helmet from "react-helmet"
const Layout = ({ location, children, pageContext, ...props }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
siteUrl
}
}
allMdx {
edges {
node {
frontmatter {
title
description
class
imageOg
imageTwitter
}
}
}
}
}
`}
render={data => (
<>
<Helmet>
<body className={pageContext.frontmatter.class} />
</Helmet>
<Container>
<Row>
<Col>
<Menu />
</Col>
</Row>
</Container>
<Container className="full-width">
<Row className="mx-0">
<Col>
<main>
<article id="content">
{children}
</article>
</main>
</Col>
</Row>
</Container>
<Footer />
</>
)}
/>
)
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
Is there any way I can create a default template inside the page's directory and then reference each MDX file as a child? For example, if it's index page then it will select home.mdx
Any help is highly appreciated.
According to the migration guide, you have several options to use a common layout across dynamic page creation:
Use the wrapPageElement API including its SSR counterpart.
Add an export default Layout statement to your MDX file, see MDX documentation on Layout.
When using the createPage action to programatically create pages, you should use the following URI pattern for your page component: your-layout-component.js?__contentFilePath=absolute-path-to-your-mdx-file.mdx. To learn more about this, head to the programmatically creating pages guide.
Given your scenario, I'd say option 2 and 3 fits better since they are easy to implement and has fewer changes to conflict to whatever you had already but. Chose wisely, whatever fits your specs (if you are or ain't using gatsby-node.js, using global wrappers as Redux, etc.).
Option 2
If you define a Layout, it will be used to wrap all content. A layout can be defined from within MDX using a default export:
export default function Layout({children}) {
return <main>{children}</main>;
}
All the things.
Or:
export {Layout as default} from './components.js'
The layout can also be passed as components.wrapper (but a local one takes precedence).
Option 3
In your gatsby-node.js, in your page generation you need to point to the layout like:
createPage({
path: `/some-slug/`,
component: `layout-component.js?__contentFilePath=${absolute-path-to-your-mdx-file.mdx}`,
context: {
id: `123456`,
},
})
Note: this approach may force you to tweak a little bit the GraphQL query to add the needed data to build the __contentFilePath properly.

Issue with rendering images on Gatsby site deployed to github pages [duplicate]

I am having trouble getting images to display on github pages. I am using a repository based page. I have added in a simple img tag with in the JSX and tried using the method described in the Gatsby documentation. I feel like I'm missing something obvious.
Here is the code
import React, { useContext } from 'react';
import AnchorLink from 'react-anchor-link-smooth-scroll';
import { ThemeContext } from 'providers/ThemeProvider';
import { Header } from 'components/theme';
import { Container, Button } from 'components/common';
import dev from 'assets/illustrations/dev.svg';
import { Wrapper, IntroWrapper, Details, Thumbnail } from './styles';
import { withPrefix } from 'gatsby'
import HeadShotPlaceHolder from 'assets/images/HeadShotPlaceHolder.jpeg'
export const Intro = () => {
const { theme } = useContext(ThemeContext);
console.log(HeadShotPlaceHolder)
return (
<Wrapper>
<Header />
<IntroWrapper as={Container}>
<Details theme={theme}>
{/* <h1>Hi There!</h1> */}
<h1>Pamela Welch</h1>
{/* <h4>I’m John and I’m a JAMStack engineer!</h4> */}
<h4>A proven professional with extensive experience in all facets of communication and marketing.</h4>
<Button as={AnchorLink} href="#contact">
Hire me
</Button>
</Details>
<Thumbnail>
{/* This is where the image tag giving me the problem is */}
<img src={ withPrefix(HeadShotPlaceHolder) } alt="I’m John and I’m a JAMStack engineer!" />
</Thumbnail>
</IntroWrapper>
</Wrapper>
);
};
and here is the result
Image Link Broken
Your code looks good, your image has its path prefixed. However, to make it effective you need to run the following snippet in the deploy command:
{
"scripts": {
"deploy": "gatsby build --prefix-paths && gh-pages -d public"
}
}
Note the --prefix-paths flag.
More information in How Gatsby Works in GitHub Pages.

React App does not have media files in build

I have a react application that is meant to display portfolio items on a page. When I run npm start they show up as expected, but on my production build (build folder) the media items are missing.
I am using require() to import the media based on a value in JSON.
Here is the code:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export class PortfolioItem extends Component {
render() {
const { img_code, id } = this.props.item;
return (
<div className='portfolio__item'>
<Link to={{
pathname: `/portfolio-details/${id}`
}}>
<img
src={require(`../assets/img_items/${img_code}`).default}
alt=''
className='img img-item'
/>
</Link>
</div>
);
}
}
export default PortfolioItem;
It is weird that this works fine locally but after git pulling the changes I made (the .default at the end) this does not work on my server.
Any ideas/comments welcome.

Gatsby Netlify build error: Can't resolve '../components/GridTemplate/GridTemplate.js' in '/opt/build/repo/src/templates'

This started happening suddenly when debugging a seemingly unrelated error on Netlify build. I do not have this issue locally. I've cleared my cache, deleted my package-lock and node module folder and updated everything, as well as ran a build without cache on Netlify. I've checked the file/folder names for case sensitive also. What could it be?
One of the templates the component is used:
import React, { Component } from 'react'
import GridTemplate from '../components/GridTemplate/GridTemplate.js'
import { graphql } from 'gatsby'
...
class Mediums extends Component {
render() {
let allTitles = []
this.props.data.allMarkdownRemark.edges.forEach( post => {
allTitles.push(post.node.frontmatter.title)
})
return (
<div style={{position: "absolute", width: "100%", height: "100%", overflow: "hidden", overflowY: "scroll"}}>
<HeaderMeta subTitle={this.props.pageContext.medium} itemGroup={this.props.data.allMarkdownRemark}/>
<GridTemplate
data={this.props.data.allMarkdownRemark.edges}
title={this.props.pageContext.medium}
pastUrl={this.props.location.pathname}
/>
</div>
)
}
}
export default Mediums
The GridTemplate component:
import React, { Component } from 'react';
import S from './imageGrid.module.sass'
import ArtImage from '../ArtImgae/ArtImage.js'
import Link from 'gatsby-link'
import { arrowSvg } from '../../img/svg-index.js'
import InlineSVG from 'svg-inline-react'
import Header from '../Header/Header.js'
import 'typeface-alegreya-sans-sc'
import 'typeface-cinzel-decorative'
import 'typeface-cinzel'
class GridTemplate extends Component {
render() {
const postLinks = this.props.data.map( post => {
const frontmatter = post.node.frontmatter
return (
<div key={post.node.fields.slug} className={S.imageItem}>
<Link
to={post.node.fields.slug}
//pass prop of cat / med paths for back button on art item
state={{pastUrl: this.props.pastUrl || null}}
>
<h2>{frontmatter.title}</h2>
<ArtImage
fluid={frontmatter.featuredImage.childImageSharp.fluid}
imageData={frontmatter}
/>
</Link>
</div>
)
})
//from context
const title = this.props.title
//const totalCount = this.props.data.allMarkdownRemark.totalCount not used
return (
<section id={S.GridTemplate}>
<div className={S.headerHolder}>
<Header to={["home", "archive"]} white={true} />
</div>
<div className={S.titleHolder}>
<Link to = "/store" className={S.storeLink} >
<InlineSVG src={arrowSvg} />
</Link>
<h1 id={S.mediumTitle}>{title}</h1>
</div>
<div className={S.imageGrid}>
{postLinks}
</div>
</section>
)
}
}
export default GridTemplate
File structure:
The component GridTemplate.js is used by categorys.js and mediums.js
Found it. Turns out my renaming of the path to the component folder to uppercase was never noticed by my Mac OS, despite appearing uppercase. On Githubs end, the path was still lower case, which was wrong. Used this gude to rename from Githubs end.
Try again deployment to netlify after changing import type-
from
import GridTemplate from '../components/GridTemplate/GridTemplate.js'
to
import GridTemplate from '../components/GridTemplate/GridTemplate'
I had the same issue when trying to deploy to Netlify:
can't resolve '../components/search/index' in '/opt/build/repo/src/pages'
My original line was:
import Search from "../components/search/index";
Please notice the lowercase for the directory name search. For some reason I had to rename the folder to uppercase Search, i.e.,:
import Search from "../components/Search/index";
and Netlify would build successfully.

gatsbyjs, reactjs - why components are rendering twice and images do not appear?

I am new to gatsbyjs and using v2.
I've 3 components - loader, header and layout.
layout.js
import React from "react"
import Helmet from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'
import Header from "./header"
import Loader from "./loader"
import 'bootstrap/dist/css/bootstrap.min.css'
import "./layout.module.css"
const Layout = ({ children }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
menuLinks {
name
link
}
}
}
}
`}
render={data => (
<React.Fragment>
<Helmet
title={'tite'}
meta={[
{ name: 'description', content: 'Sample' },
{ name: 'keywords', content: 'sample, something' },
]}
>
</Helmet>
<Loader />
<Header menuLinks={data.site.siteMetadata.menuLinks} siteTitle={data.site.siteMetadata.title} />
<div>{children}</div>
</React.Fragment>
)}
/>
)
export default Layout
In index.js
import React from 'react'
import Layout from "../components/layout"
export default () => (
<Layout>
</Layout>
)
Every component is being rendered twice as shown in screenshot.
Another issue I am facing with images. All the images are in src/images/ and when I use it as below in header component:
import React from "react"
import { Link } from 'gatsby'
import styles from "./layout.module.css"
const logo = 'src/images/logo.png';
const Header = ({ siteTitle, menuLinks }) => (
<header className={styles.header_area}>
<nav className={`${styles.navbar} navbar-expand-lg ${styles.menu_one} ${styles.menu_four}`}>
<div className="container">
<a className="navbar-brand sticky_logo" href="#">
<img src={logo} alt="logo" />
The image doesn't show up on a page. I checked Source in chrome developer tools and found that images are not being served via webpack.
So, why components render twice and why image doesn't show up ? what am I missing or doing worng here ?
I had the same issue when using the gatsby-plugin-layout plugin. The doc is not really clear, but when using the gatsby-plugin-layout plugin, you don't need to wrap your page between the Layout component. That plugin takes care of this automatically. If you explicitly wrap your JSX between the Layout component, the Layout is rendered twice.
I'm not sure why your page is loading double components, are you coming to the site directly, or from another path?
For your image not showing up, this is why:
Everything in your src folder is meant to be dynamic, meaning it won't be served directly. If you want to include image statically, you can create a public folder in your root directory (at the same level with src folder), and put images in there. Anything in this public folder will be served directly. So for example, you can have this structure:
|-- src
`-- public
`-- images
`-- logo.png
Then in your code, you can include the path like
<img src="/images/logo.png" alt="logo" />
I think for a logo like your use case, this method is sufficient. However, if you always link images like this, you'll be missing out a lot of gatsby's cool feature. For example, gatsby can load your image lazily, or optimize the file size! You can learn more here (gatsby official blog).

Resources