This question already has answers here:
Environment variables not working (Next.JS 9.4.4)
(8 answers)
Closed 9 months ago.
I am using Sanity image url in my project and I am getting this error in my console page that says
next-dev.js?3515:25 Warning: Prop src did not match.
Server:"https://cdn.sanity.io/images/jbcyg7kh/production/4f6d8f5ae1bed2647201bfcaed2f270897b92306-800x533.jpg"
Client: "https://cdn.sanity.io/images/jbcyg7kh/undefined/4f6d8f5ae1bed2647201bfcaed2f270897b92306-800x533.jpg"
import sanityClient from "#sanity/client";
import imageUrlBuilder from "#sanity/image-url";
export const client = sanityClient({
projectId:"projectId",
dataset:process.env.NEXT_SANITY_DATASET,
useCdn: true,
apiVersion:"2022-05-13"
});
const builder = imageUrlBuilder(client)
export const urlFor= (source) =>builder.image(source)
import Link from "next/link";
import React from "react";
import { urlFor } from "../lib/client";
function Product({ product: { name, image, price, description, slug } }) {
return (
<div>
<Link href={`/product/${slug.current}`}>
<div>
<img src={urlFor(image[0])} alt="" />
<h4>{name}</h4>
<p>₦{price}</p>
<p>{description}</p>
</div>
</Link>
</div>
);
}
export default Product;
It looks like the urlBuilder builds the URL builder from sanityClient. Judging by the pattern of the URLs,
Server:"https://cdn.sanity.io/images/jbcyg7kh/production/4f6d8f5ae1bed2647201bfcaed2f270897b92306-800x533.jpg"
Client:"https://cdn.sanity.io/images/jbcyg7kh/undefined/4f6d8f5ae1bed2647201bfcaed2f270897b92306-800x533.jpg"
You can see that server has process.env.NEXT_SANITY_DATASET set, while client does not. You can add this environment variable by following the steps here.
Related
The detail of the problem is that I'm not getting the data we expected within our code. We have set up the following to see within our project folder.
Within webpack.config.js we set up resolve.alias in the webpack configuration, so we can include it in the resolve object of the webpack config file.
This is the file:
module.exports = {
// other webpack config options
resolve: {
alias: {
// Create an alias for the queries folder
queries: path.resolve(__dirname, 'src/queries'),
},
},
};
This is what are path name will look like:
import { homeQuery } from "queries/navigation/homeLinks";
Created a webpack.config.js.
Console.log are data of homeData and HomeData.homelink.
Tested the query within GraphQL Playground in Hygraph.
From there I checked the console in the browser.
I have found out we are not getting the query in our body that we want but we have tested the query within GraphQL Playground. We have found out that we correctly getting the correct query that we want to get into our data within console.log.
This is a query for the homepage:
import { gql } from "#apollo/client";
export const homeQuery = gql`
query homeLinks {
pages(
where: {id: "clbzl7ovpe64d0ak5qh7o2p8f", slug: "Home"}
stage: PUBLISHED
locales: en
) {
id
slug
title
}
}`
;
This where we console are data for the homepage:
console.log(homeData && homeData?.homeLink?.pages);
console.log(homeData)
import React from 'react';
import '../assets/style/navigation.css';
import { useQuery } from '#apollo/client';
import { BrowserRouter as Router, Link } from 'react-router-dom';
import { homeQuery } from "../queries/navigation/homeLinks";
import { logoassetsQuery } from "../queries/navigation/logoLinks";
export default function App() {
const { loading: logoAssetsLoading, error: logoassetsData } = useQuery(logoassetsQuery);
//This is query for the pages.
const { loading: homeLoading, error: homeError, data: homeData } = useQuery(homeQuery);
//This is for front-end error message.
if (logoAssetsLoading) return <p>Loading Logo Assets...</p>;
if (homeLoading) return <p>Loading... this page links.</p>
if (homeError) return <p>Error :( this page don't work.</p>;
// Debugging step 1: Check the value of data.navigation
console.log(homeData && homeData.homeLinks)
console.log(homeData)
// Debugging step 2: Check the value of data
//console.log(data);
return (
<div className='navigation'>
<div className='full_width_container'>
<div className='wrapper'>
<Router>
<React.Fragment>
<nav>
<div className='nav_groups logo'>
{homeData && homeData?.homeLinks?.pages && homeData?.homeLinks?.page(link => (
<li key={link?.id}>
<Link to={`/${link?.slug}`}>
<img src={logoassetsData?.logoAssets} alt='main logo'/>
</Link>
</li>
))}
</div>
</nav>
</React.Fragment>
</Router>
</div>
</div>
</div>
);
}
I have used pdf-viewer-reactjs into my Next.js project. But getting following error.
error - ./node_modules/pdfjs-dist/build/pdf.js 2094:26
Module parse failed: Unexpected token (2094:26)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| async destroy() {
| this.destroyed = true;
> await this._transport?.destroy();
| this._transport = null;
|
So far I've tried following both ways but nothing worked for me!
How to use this npm into my project without any errors?
The code (Way 1):
import React from 'react';
import StudentPortalLayout from "../../../components/Layout/StudentLayout";
import dynamic from "next/dynamic";
const PDFViewer = dynamic(() => import("pdf-viewer-reactjs"), {
ssr: false
});
function PDFView() {
return (
<StudentPortalLayout hideSidebar={true}>
<PDFViewer
document={{
url: 'https://arxiv.org/pdf/quant-ph/0410100.pdf',
}}
/>
</StudentPortalLayout>
)
}
export default PDFView;
The code (Way 2):
import React from 'react';
import StudentPortalLayout from "../../../components/Layout/StudentLayout";
import PDFViewer from 'pdf-viewer-reactjs'
function PDFView() {
return (
<StudentPortalLayout hideSidebar={true}>
<PDFViewer
document={{
url: 'https://arxiv.org/pdf/quant-ph/0410100.pdf',
}}
/>
</StudentPortalLayout>
)
}
export default PDFView;
I was able to run the following code successfully, however it requires additional steps
Install the babel runtime - yarn add #babel/runtime - courtesy this post.
Material UI icon gives an error, so similarly add the material UI dependencies
Assuming this is what you want:
Stackblitz - https://stackblitz.com/edit/nextjs-utkd32?file=pages%2Findex.js
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import PDFViewer from 'pdf-viewer-reactjs';
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
</Head>
<main className={styles.main}>
<PDFViewer
document={{
url: 'https://arxiv.org/pdf/quant-ph/0410100.pdf',
}}
/>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
</a>
</footer>
</div>
);
}
Dynamic Imports
If you want to do a dynamic import as you were trying to do above, the export of the individual module maybe need to linked to - potentially pdf-viewer-reactjs/pdf-viewer-reactjs - This needs more to be looked into.
I'm trying to show a dynamically imported image, but it's not working with the error
'Cannot find module'
This is my component
<template>
<div class="footer">
<div v-for="footerItem in getters" :key="footerItem.id">
<img :src="methods.requireImage(footerItem.icon)" alt="">
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import { useStore } from '#/store'
import { requireImage } from '#/modules/images'
export default defineComponent({
name: 'Footer',
setup () {
const store = useStore()
const methods = {
requireImage
}
return {
getters: store.getters.getFooterItems,
methods
}
}
})
</script>
And this is module
export const requireImage = async (link: string) => {
// return require(link)
const image = await import(link)
return image
// const images = require.context('../assets', false)
// return images('color-circle.svg')
}
Commented out code not working
If you pass the full path to require in a variable, Webpack can't load the image. This is roughly because it's a build-time tool, and the path is created at runtime. If you hard-code at least some of the path though, that will be sufficient:
export const requireImage = link => {
return require(`#/assets/${link}`);
}
Note: Removed the unnecessary async or the return value would be a promise
Your variable footerItem.icon should just contain the filename color-circle.svg now that some of the path is hard-coded in the call to require. With that done, you can use the method in the template as you wanted:
<img :src="methods.requireImage(footerItem.icon)" alt="">
Be aware that at the moment your wrapper method is unnecessary because you could get the same result from:
<img :src="require(`#/assets/${footerItem.icon}`)">
I am working on a Gatsby website, and I keep getting "TypeError: Cannot read property 'childImageFluid' of undefined"
The code I have is this in my Project.js file
import React from "react"
import PropTypes from "prop-types"
import Image from "gatsby-image"
import { FaGithubSquare, FaShareSquare } from "react-icons/fa"
const Project = ({description, title, github, stack, url, image, index}) => {
return (
<article className="project">
<Image fluid={image.childImageFluid.fluid} className="project-img" />
</article>
)
}
Project.propTypes = {}
export default Project
and I have the graphql set up in the index.js file where it will be displayed, and everything is working as it should in graphql...
export const query = graphql`
{
allStrapiProjects(filter: { featured: { eq: true } }) {
nodes {
github
id
description
title
url
image {
childImageSharp {
fluid {
...GatsbyImageSharpFluid
}
}
}
stack {
id
title
}
}
}
}
`
everything up to the what I am working on in the Project.js file is in my github - https://github.com/matthewbert86/gatsby-site but all of that code is in the first code section above.
When you use a page query in GraphQL, your gathered data is stored inside a data object (as a props). You need to iterate through it until you get your fluid image. It should be in: props.data.allStrapiProjects.nodes.image.childImageFluid.fluid. Since you are destructuring everything in your <Project> component:
const Project = ({ data }) => {
let { description, title, github, stack, url, image } = data.allStrapiProjects.nodes; // your data is here
return (
<article className="project">
<Img fluid={data.allStrapiProjects.nodes.image.childImageFluid.fluid} className="project-img" />
</article>
)
}
After destructuring, you can refactor it to:
<Img fluid={image.childImageFluid.fluid} className="project-img" />
Another point, I guess that the gatsby-image import should be Img, not Image.
Im building a blog with Gatsby and I'm trying to display a hero image on each post page with the image path that is defined in each posts front matter. But, I'm getting this error from my hero component:
TypeError: Cannot read property 'image' of undefined
Here is my code:
Post front matter
---
path: /blog-post1
title: Blog Post 1
image: ../../images/blog-post-1.jpg
description: Blog post description
---
Hero.js
import React from 'react'
import Img from "gatsby-image";
const Hero = props => (
<section className="hero is-large">
<Img
fluid={props.frontmatter.image.childImageSharp.resize}
/>
<div className="hero-body">
</div>
</section>
);
export default Hero
Post.js
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout';
import Hero from '../components/hero';
const PostTemplate = ({ data }) => {
const { markdownRemark } = data;
const { frontmatter, html } = markdownRemark;
return (
<Layout>
<Hero headerImage={frontmatter.image} />
<section class="section">
<div className="container is-medium">
<div dangerouslySetInnerHTML={{__html: html}} />
</div>
</section>
</Layout>
)
}
export default PostTemplate;
export const pageQuery = graphql`
query($path: String!) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
html
frontmatter {
date
path
title
description
image {
childImageSharp {
resize(width: 1500, height: 1500) {
src
}
fluid(maxWidth: 786) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
`;
Any ideas on what's happening? Thanks in advance.
I am assuming you have data in frontmatter variable all the time. If you look at how you are calling Hero Component, where you are passing data as headerImage.
<Hero headerImage={frontmatter.image} />
If you look at Hero component you are reading it as frontmatter, You can do following changes and check.
You can add the condition to Img component to avoid the errors because of missing data.
{
props.headerImage && props.headerImage.image && props.headerImage.image.childImageSharp
<Img
fluid={props.headerImage.image.childImageSharp.resize}
/>
}
I figured out was the issue.
In my hero.js, I was calling the image using {props.frontmatter.image.childImageSharp.resize}
But in my post.js I was passing the data into the hero component like this <Hero headerImage={frontmatter.image} />
So, it was trying to find frontmatter.image.image, which doesn't exist. All I had to do was remove the .image like this <Img fluid={props.headerImage.childImageSharp.resize} />