Working with images local files in Gatsby.js - reactjs

I am trying to render a headshot for each artist displayed on the page. The artist data comes from a Json file, and the images are located in images/artists/headshots. I am using the regular img tag, but for some reason nothing is displaying on the page. Any help any one can give would be greatly appreciated.
import React from 'react'
import PropTypes from 'prop-types'
import { StaticImage } from 'gatsby-plugin-image'
import { useStyles } from './styles'
const ArtistsPage = ({ data }) => {
const classes = useStyles()
return (
<section>
<article className={classes.artistsBackground}>
<div className={classes.heroLayoutContainer}>
<h3 className={classes.title}>MEET THE ARTISTS</h3>
<StaticImage
className={classes.heroImage}
src='../../images/artists/hero-images/hero-image-artists.jpg'
alt='hero-image-artists'
placeholder='blurred'
/>
</div>
</article>
<article className={classes.artistsContainer}>
<div className={classes.flexContainer}>
{data.allArtistsJson.edges
.map(({ node }, idx) => {
const artist = `${node.firstName}+${node.lastName}`
.split('+')
.join(' ')
return (
<div className={classes.flexItem} key={idx}>
<div>
<img
src={`../../images/artists/headshots/${artist} Headshot.jpg`}
alt='artist-headshot'
/>
</div>
<div className={classes.artistCardName}>
{`${node.firstName} ${node.lastName}`.toUpperCase()}
</div>
<div className={classes.artistCardText}>{node.city}</div>
<div className={classes.artistCardText}>
{node.currentTeam}
</div>
</div>
)
})}
</div>
</article>
</section>
)
}
export default ArtistsPage
My image files are set up as:
FirstName LastName Headshots.jpg

I think your issue may comes from the white spaces in the naming. Your code looks good at first sight so try renaming your images with underscore or in camelCase:
<img
src={`../../images/artists/headshots/${artist}_Headshot.jpg`}
alt='artist-headshot'
/>

After much research and the nice people on Gatsby discord I found the answer to be… in a scenario like this I needed to add require().default.
Ex:
<img
src={require(../../images/artists/headshots/${artist} Headshot.jpg).default}
alt='artist-headshot'
/>

Related

about gatsby link issue

I created my own blog with gatsby and contentful using template. And I was tring to change subdirctory of my arcticels. article URLs are working now but links in index page is not working.
import React from 'react'
import { Link } from 'gatsby'
import { GatsbyImage } from 'gatsby-plugin-image'
import Container from './container'
import Tags from './tags'
import * as styles from './article-preview.module.css'
const ArticlePreview = ({ posts }) => {
if (!posts) return null
if (!Array.isArray(posts)) return null
return (
<Container>
<ul className={styles.articleList}>
{posts.map((post) => {
return (
<li key={post.slug}>
<Link to={`/${post.category}/${post.slug}`} className={styles.link}>
<GatsbyImage alt="" image={post.heroImage.gatsbyImageData} />
<h2 className={styles.title}>{post.title}</h2>
</Link>
<div
dangerouslySetInnerHTML={{
__html: post.description.childMarkdownRemark.html,
}}
/>
<div className={styles.meta}>
<small className="meta">{post.publishDate}</small>
<Tags tags={post.tags} />
</div>
</li>
)
})}
</ul>
</Container>
)
}
export default ArticlePreview
I changed to <Link to={/${post.category}/${post.slug}} from <Link to={/${post.slug}}. but somehow links are like http://localhost:8000/undefined/(article-slug). It shold be category name as I set up in Comtentful insted of 'undefined'.
do you have any suggestions?
if I use subdir like /blog/, its working. and Link to={/${post.slug}/${post.slug}} also work.

I Create a react.js component and it doesn't render

I Create a component and it doesn't render (react js) < --- completely newbie react js user
first i create well structure of a card in list
meetupitems.js
import { Action } from 'history';
import css from './Meetupitems.module.css';
function Meetupitem(props) {
<li className={css.item}>
<div className={css.image}>
<image src={props.image} alt={props.title} />
</div>
<div className={css.content}>
<h3>{props.title}</h3>
<address>{props.address}</address>
<p>{props.description}</p>
</div>
<div className={css.actions}>
<button></button>
</div>
</li>;
}
export default Meetupitem;
then use map() to create card list from "list of data"
Meetuplist.js
import Meetupitem from "./Meetupitems";
import css from "./Meetuplist.module.css";
function Meetuplist(props) {
return (
<ul className={css.list}>
{props.meetups.map((meetup) => (
<Meetupitem
key={meetup.id}
title={meetup.title}
image={meetup.image}
address={meetup.address}
description={meetup.description}
/>
))}
</ul>
);
}
export default Meetuplist;
and when i'm trying to use it
Allmeetup.js
import Meetupitem from "./Meetupitems";
import css from "./Meetuplist.module.css";
function Meetuplist(props) {
return (
<ul className={css.list}>
{props.meetups.map((meetup) => (
<Meetupitem
key={meetup.id}
title={meetup.title}
image={meetup.image}
address={meetup.address}
description={meetup.description}
/>
))}
</ul>
);
}
export default Meetuplist;
the result I saw was a blank page at the index route(where the list should show)
but others route was fine
I can't figure out what's wrong
I think the issue is nothing is being returned from your Meetupitem component. There is no return statement in it.
I believe if you look in console in chrome dev tools, you will be able to see the error messages for it.
Try changing it to as shown below:
import { Action } from 'history';
import css from './Meetupitems.module.css';
function Meetupitem(props) {
return (
<li className={css.item}>
<div className={css.image}>
<image src={props.image} alt={props.title} />
</div>
<div className={css.content}>
<h3>{props.title}</h3>
<address>{props.address}</address>
<p>{props.description}</p>
</div>
<div className={css.actions}>
<button></button>
</div>
</li>;
)
}
export default Meetupitem;

getStaticProps not working from components folder

Recently I made a question about this problem: typeError: Cannot read property 'map' of undefined.
I want to use a component with getStaticProps and put it in my pages/index.js, but I can't with my current code. BUT, if I put this component as a page (pages/component.js) and open like a different page it just work as it should do.
The component Galery.js code:
import styles from '../styles/galery.module.css'
import Image from 'next/image'
import Link from 'next/link'
import photo from '../public/01.png'
export const getStaticProps = async () => {
const res = await fetch('https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card');
const datas = await res.json();
return {
props: { datas }
}
}
const Galery = ({ datas }) => {
return (
<div className={styles.galeryPage}>
<h1 className={styles.title}>Projetos</h1>
<div className={styles.galery}>
<div className={styles.categoryWrapper}>
<h4 className={styles.subTitle}>Escritório</h4>
<div className={styles.lineWrapper}>
<a className={styles.leftArrow}>❮</a>
<div className={styles.line}>
{datas.map((data) => (
<div className={styles.imageBox}>
<Image src={photo} width={400} height={200} layout="responsive" lazy="true" placeholder="blur" />
<div className={styles.linkContent}>
<span className={styles.name} key={data.id}>{data.name}</span>
<Link href=""><a className={styles.link}>Veja Mais!</a></Link>
</div>
</div>
))}
</div>
<a className={styles.rightArrow}>❯</a>
</div>
</div>
</div>
</div>
);
}
export default Galery;
API link: https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card
And this is the structure that I would like to have:
Desirable Structure
And this is the structure that works as a page:
Structure that works
What I should do to work as I planned?
Data fetching methods like getStaticProps can only be used from page components (components inside pages folder). I'd suggest you fetch the data at the page level in index.js, and pass it down to your Galery component.
juliomalves is correct! Thanks.

Caching in Gatsby JS

I have this Gatsby app where when I visit home page everything loads at first including the Testimonials section. However, when I visit another page, for instance the Blog list page and then click on the link back to homepage the data on Testimonials component won't load and you will see a blank area of the app where the Testimonials section is placed. In order to see the Testimonials list, you will have the refresh the page again.
For the record the data on my Testimonials component are being pulled out on Strapi JS that is deployed on Heroku.
So far I got this on my index.js:
import React from "react"
import { graphql } from "gatsby"
import Layout from "../components/Layout"
import Header from "../components/Header"
import Testimonials from '../components/Testimonials'
import Blogs from '../components/Blogs'
import SEO from '../components/SEO'
export default function Home({ data }) {
const {
allStrapiBlogs: { nodes:blogs },
} = data
return (
<>
<SEO />
<div className="main-container">
<Layout>
<Header />
<Testimonials title="Testimonials" />
<Blogs title="Latest Blogs" blogs={blogs} showAllBlogLinks/>
<Map />
</Layout>
</div>
</>
)
}
export const query = graphql`
{
allStrapiBlogs(filter: {featured: {eq: true}}, sort: {fields: published_date, order: DESC}, limit: 6) {
nodes {
id
title
content
slug
published_date(formatString: "MMMM DD, YYYY")
featured_image {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`
And then on my Testimonials.js component:
import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import Image from "gatsby-image"
import { FaStar } from "react-icons/fa"
import Title from './Title'
const query = graphql`
{
allStrapiTestimonials {
nodes {
id
name
cite
text
photo {
childImageSharp {
fluid{
...GatsbyImageSharpFluid_withWebp
}
}
}
}
}
}
`
const Testimonials = ({ title }) => {
const data = useStaticQuery(query)
const { allStrapiTestimonials: { nodes:testimonials } } = data
return (
<div className="testimonial-section section-padding" id="testimonial" data-aos="zoom-in">
<div className="container">
<div className="row">
<div className="col-lg-12">
<div className="section-title-two center">
<Title title={title} />
</div>
</div>
</div>
<div className="testimonial-wrap row">
<div className="testimonial-slider owl-carousel">
{ testimonials.map(item => {
const { id, name, cite, text, photo } = item
return(
<div className="col-xl-8 col-lg-10 col-12 ml-auto mr-auto" key={id}>
<div className="testimonial-item mt-40">
<div className="testimonial_img">
<Image fluid={photo.childImageSharp.fluid} alt={name} style={{ position: "absolute", overflow: "visible", display: "block", width: "211px", height: "207px" }} />
</div>
<div className="testimonial_content xs-mt-40">
<div className="testimonial_content_item mb-30">
<div className="testimonial_content__pro">
<h4 className="mb-10">{ name }</h4>
<p>{ cite }</p>
</div>
<ul className="d-none d-sm-inline-block">
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
<li><FaStar></FaStar></li>
</ul>
</div>
<div>
<p>{ text } </p>
</div>
</div>
</div>
</div>
)
})}
</div>
</div>
</div>
</div>
)
}
export default Testimonials
Any idea what's causing this error? How can I fix it?
I've faced a similar issue a few months ago and the fix depends strictly on the implementation and your code. Basically, what is happening is that React's doesn't understand that he needs to rehydrate some components because pointing to some global objects as window or document of the DOM, outside the React's ecosystem (without using states) may block that rehydration, in your cause, because of jQuery.
All the possible solutions that bypass this issue will be patches (like trying to add the cache). The ideal solution would avoid using jQuery, which points directly to the DOM, with React, which manipulates the virtual DOM (vDOM).
There's nothing wrong with the code you've shared, however, based on some other questions that you did, you are using jQuery and using the window object, which prevents the rehydration of some React components. You should get rid of jQuery or using some React-based approach. Something like this should do the trick to force a loader across the whole site:
const Layout = ({ children }) => {
const [loader, setLoader]=useState(true);
useEffect(()=>{
setTimeout(()=> {
setLoader(false)
}, 400)
}, [])
return <section className={`site__wrapper`}>
<Header />
<main>{loader ? <Preloader/> : children}</main>
</section>;
};

how to select clicked element in reactjs?

I am new to reactjs in this i have defined components and i am passing title to audio cards and by using title i am also defining source of the audio files. and after clicking on that particular component i want to play that particular audio file.
in js we can achieve this using $(this).find();
but in reactjs how to do it can anyone help me
import React from 'react';
import AudioCard from './AudioCard';
import '../css/RecommendedAudios.css';
function RecommandedAudios() {
return (
<div className="recommandedaudios">
<h2>Recommanded</h2>
<div className="recommandedaudios_audios">
<AudioCard title="Arrows to Athens - Alive" />
<AudioCard title="Arrows to Athens - Dust & Gold" />
<AudioCard title="Arrows to Athens - Stars" />
<AudioCard title="Arrows to Athens - Used to be" />
<AudioCard title="Bryan Adams - Here I am" />
<AudioCard title="My Heart Belongs to You" />
<AudioCard title="Ravenscode - My Escape" />
</div>
</div>
);
}
export default RecommandedAudios;
import React from 'react';
import '../css/AudioCard.css';
import PlayArrowIcon from '#material-ui/icons/PlayArrow';
function AudioCard({ title, timestamp }) {
var playsong = () => {
const select = document.querySelector("audio");
select.play();
};
return (
<div onClick={playsong} className="audiocard">
<PlayArrowIcon />
<div className="audiocard_info">
<div className="audiocard_title">
<h5>{title}</h5>
<audio src={require(`../sounds/${title}.mp3`)}></audio>
</div>
</div>
</div>
);
}
export default AudioCard;
document.querySelector("audio") will return the first "audio" tag in the HTML, not the specific one you're looking for
you can use ref:
import React, { useRef } from 'react'
function AudioCard({ title, timestamp }) {
const audioEl = useRef(null);
const playsong = () => audioEl.current.play();
return (
<div onClick={playsong} className="audiocard">
<PlayArrowIcon />
<div className="audiocard_info">
<div className="audiocard_title">
<h5>{title}</h5>
<audio ref={audioEl} src={require(`../sounds/${title}.mp3`)}></audio>
</div>
</div>
</div>
);
}
You can use react-audio-player instead of using query selector and HTML audio tag
you can install it by
npm install --save react-audio-player
and inport the library to your code and use
import ReactAudioPlayer from 'react-audio-player';
const [audio,ReferAudio] = useState()
...........
<div onClick={playsong} className="audiocard">
<PlayArrowIcon />
<div className="audiocard_info">
<div className="audiocard_title">
<h5>{title}</h5>
<ReactAudioPlayer
src={require(`../sounds/${title}.mp3`)}
controls
ref={(e) => { ReferAudio(e) }}
/>
</div>
</div>
</div>
you can access the player by using audio
you can lern more here

Resources