React App does not have media files in build - reactjs

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.

Related

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.

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

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.

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.

How to precache files from AWS to my React app with service-worker?

I'm making a game on React and I want to precache all files from AWS to user machine and then use them from serviceworker.
I found such code
import React, { Component, lazy } from 'react';
import AvatarComponent from './AvatarComponent';
class App extends Component {
constructor(props) {
super(props);
this.state = {
details: false
}
}
showDetails() {
this.setState({ details: true });
}
render() {
const { details } = this.state;
return (
<div className="App">
{ !details && <button onClick={() => this.showDetails()}>CLICK ME</button> }
{ details &&
<div>
<AvatarComponent />
</div>
}
</div>
);
}
}
export default App;
in AvatarComponent I have
import React from 'react';
import imageSrc from './pupper.jpg';
const AvatarComponent = () => (
<img alt="Puppy" src={imageSrc} />
)
export default AvatarComponent;
This app works as expected - when I click on CLICK ME button I see that pupper.jpg image is loaded from serviceworker.
What do I need to do to precache and save images, audios and videos stored on Amazon Simple Storage Service (Amazon S3)?
Here is working example that I have https://glitch.com/~daffy-snowy-suggestion
Amazon S3 is not a CDN in that it caches files. Use CloudFront for caching files stored on S3.

Initialize script in componentDidMount – runs every route change

I am working on a navbar for my react app (using gatsbyjs to be precise). In the navbar I have a marquee that I initialize in the navbar component in componentDidMount.
It works as intended, but upon every route change componentDidMount will run again which results in the marquee speeding up for every page change, making it go faster and faster.
Is this expected behaviour? And if so, how do I make sure that the script is only run once?
navbar.js
import React from 'react';
import { Link } from 'gatsby';
import styles from '../styles/navbar.module.css';
import NewsMarquee from './newsMarquee';
import Marquee3k from 'marquee3000';
const topLevelNav = [
{
href: '/news',
label: <NewsMarquee/>,
extraClass: styles.navLinkNews,
mediaQueryClass: styles.navLinkHiddenSmall,
},
];
export default class Navbar extends React.Component {
componentDidMount() {
Marquee3k.init();
}
render() {
return (
<div>
<header className={styles.navbar} role="banner">
<nav className={styles.nav}>
{topLevelNav.map(({ href, label, extraClass = '', mediaQueryClass = '' }) => (
<Link
key={label}
to={href}
className={`${styles.navLink} ${extraClass} ${mediaQueryClass} ${menuItemsHidden}`}
activeClassName={styles.navLinkActive}
>
{label}
</Link>
))}
</nav>
</header>
</div>
)
}
}
newsMarquee.js
import React from 'react';
import { StaticQuery, graphql } from "gatsby";
import styles from '../styles/newsMarquee.module.css';
export default () => (
<StaticQuery
query={graphql`
query {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC } limit: 10) {
totalCount
edges {
node {
id
frontmatter {
title
date(formatString: "YYYY.MM.DD")
}
fields {
slug
}
}
}
}
}
`}
render={data => (
<div className={`marquee3k ${styles.marquee}`}>
<div>
{data.allMarkdownRemark.edges.map(({ node }) => (
<span className={styles.marqueeItem} key={node.id}>
{node.frontmatter.date} {node.frontmatter.title}
</span>
))}
</div>
</div>
)}
/>
)
Since I'm using GatsbyJS I went with this plugin from V1, which makes my layout component persist across pages.
gatsby-plugin-layout
This plugin enables adding components which live above the page components and persist across page changes.
This can be helpful for:
Persisting layout between page changes for e.g. animating navigation
Storing state when navigating pages
Custom error handling using componentDidCatch
Inject additional data into pages using React Context.
This plugin reimplements the behavior of layout components in gatsby#1, which was removed in version 2.

Resources