I'm developing a blog on next.js with sanity.io, and I'm having trouble using the code-input plugin.
What I do have
I'm able to use the code component block on sanity, which looks something like this:
Everything good on the sanity side. My problem comes with using it on the next.js [slug].js file.
I have this error prompt out:
This issue with this is that I don't have a serializer.js file/component anywhere on my code, not even on the studio root folder. I've seen this applies for gatsby but I don't know how to apply it for Next.js
This is what I currently Have:
import groq from 'groq'
import imageUrlBuilder from '#sanity/image-url'
import BlockContent from '#sanity/block-content-to-react'
import client from '../../client'
import Layout from '../../components/layout'
import utilStyles from '../../styles/utils.module.css'
import styles from '../../components/layout.module.css'
function urlFor (source) {
return imageUrlBuilder(client).image(source)
}
const Post = (props) => {
const {
title = 'Missing title',
name = 'Missing name',
categories,
authorImage,
mainImage,
code,
body = []
} = props
console.log(props)
return (
<Layout>
<article>
<div className={styles.container}>
<figure>
<img src={urlFor(mainImage).url()} />
</figure>
<h1 className={utilStyles.headingXl}>{title}</h1>
{categories && (
<ul className="inline">
Category:
{categories.map(category =>
<li key={category}>
<span className="inline-flex items-center justify-center px-2 py-1 text-xs font-bold leading-none text-indigo-100 bg-indigo-700 rounded">{category}</span>
</li>)}
</ul>
)}
<BlockContent
blocks={body}
imageOptions={{fit: 'max'}}
{...client.config()}
{...code}
/>
</div>
</article>
</Layout>
)
}
const query = groq ` *[_type == "post" && slug.current == $slug][0]{
title,
"name": author->name,
"categories": categories[]->title,
mainImage,
code,
"authorImage": author->image,
body,
}`
Post.getInitialProps = async function(context) {
const {slug = ""} = context.query
return await client.fetch(query, { slug })
}
export default Post
I really would appreciate some help here! Thanks <3
You can pass a serializer for the code block type to your BlockContent using the serializers prop.
const serializers = {
types: {
code: props => (
<pre data-language={props.node.language}>
<code>{props.node.code}</code>
</pre>
)
}
}
// ...
<BlockContent
blocks={body}
imageOptions={{fit: 'max'}}
{...client.config()}
{...code}
serializers={serializers}
/>
Related
I am creating dev.to clone for react js practice when
trying to render markdown in react-markdown it doesn't render properly,
here it is:
Post.js
import React, { useState } from 'react';
import ReactMarkdown from 'react-markdown';
import SyntexHighlight from '../../components/SyntexHighlight';
const Post = ({ post }: any) => {
return (
<main className="h-full bg-white rounded-md border">
<header>
.........
</header>
<div
className=" leading-8 marker:text-black max-w-2xl mx-auto py-6 prose
prose-lg prose-p:block prose-li:py-[0.5] prose-li:my-0 prose-a:text-blue-600
hover:prose-a:text-blue-500 prose-code:text-sm prose-code:bg-gray-200
prose-code:p-1 prose-code:rounded prose-img:mx-auto "
>
<ReactMarkdown components={SyntexHighlight}>{post.body}</ReactMarkdown>
</div>
<section className="border-t-2 px-8 py-4">
........
</section>
</main>
);
};
export default Post;
SyntexHighlight.js
import React from 'react';
import { Prism } from 'react-syntax-highlighter';
import { oneDark } from 'react-syntax-highlighter/dist/cjs/styles/prism';
const SyntexHighlight = {
code({ node, inline, className, ...props }: any) {
const match = /language-(\w+)/.exec(className || '');
return !inline && match ? (
<Prism style={oneDark} language={match[1]} PreTag="div" className="codeStyle" {...props} />
) : (
<code className={className} {...props} />
);
},
};
export default SyntexHighlight;
It doesn't render properly
markdown render problem
markdown render problem
markdown render problem
I tried "json2md" package after getting JSON string form node server still not working
when i try "json2md" data to separate variable
data variable
<div
className=" leading-8 marker:text-black max-w-2xl mx-auto py-6 prose
prose-lg prose-p:block prose-li:py-[0.5] prose-li:my-0 prose-a:text-blue-600
hover:prose-a:text-blue-500 prose-code:text-sm prose-code:bg-gray-200
prose-code:p-1 prose-code:rounded prose-img:mx-auto "
>
<ReactMarkdown components={SyntexHighlight}>{MarkdownFile}</ReactMarkdown>
</div>
Now its working properly
it's working
it's working
it's working
i don't know what is the problem ???
In my Next js app I'm Passing an Object through pages. what I did is compress my array of objects into JSON JSON.stringify(result) from index page and in my second page I parsed it JSON.parse(props.router.query.result). this worked great. but the issue is when reloading the page the browser prompts
This page isn’t workingIf the problem continues, contact the site owner.
HTTP ERROR 431
I know this message indicates for long url head. so is there a way for me to shorten this?
index page
<Link href=
{{pathname: "/tv-shows",
query: {
result: JSON.stringify(result),
//result: [result],
img: img,
index: index,
}}} key={index}
>
<div className=' relative snap-center h-56 w-96 rounded-3xl hover:rounded-3xl hover:scale-110 hover:transition-all hover:duration-200 hover:ease-in ease-out duration-200 '>
<Image
src={img}
layout="fill"
objectFit="cover"
className={`h-full w-full bg-cover bg-no-repeat rounded-3xl hover:rounded-3xl hover:scale-110 hover:transition-all hover:duration-200 hover:ease-in ease-out duration-200`} />
</div></Link>
in second page
const TvShows = (props) => {
const [result, setResult] = useState([]);
const [index, setIndex] = useState("");
const [img, setImg] = useState("");
useEffect(()=>{
console.log("first")
console.log(props.router.query);
if (props.router.query.result){
const query = props.router.query;
const res = JSON.parse(query.result);
setResult(res);
setIndex(query.index);
setImg(query.img);
//console.log(JSON.parse(props.router.query.result));
}
},[props.router.query ])
return (
<div className=''>
<Head>
<title>{Popular[Number(index)].title} | </title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Background result={result} img={img} index={index} />
{/* <Background img={img} index={index} /> */}
<div className='cursor-default px-10'>
<div className=' text-xl pt-5 pb-5'>Full Episodes </div>
{/* <Contents result={result} index={index}/> */}
</div>
</div>
)
}
export default withRouter(TvShows)
please help me with the fix
Based on comments to your original post, I deducted that you do not want to shorten a very long URL, but you are trying to pass data between subpages of Next app and save it so it is accessible after page refresh. What you can do to solve your issue is saving your result to localStorage every time it changes:
useEffect(() => {
localStorage.setItem("result", JSON.stringify(result))
}, [result])
And then, in your second page read the data:
useEffect(()=>{
const result = JSON.parse(localStorage.getItem("result"))
console.log("first")
console.log(result);
if (result){
setResult(result);
setIndex(query.index);
setImg(query.img);
}
}, [])
After comments to this Answer:
I think that what you want to do is creating a page tv-shows, which will display the details of one Youtube playlist. Best way to get this working is by creating dynamic routes.
Create the following directory structure in your app:
root
└── pages
└── tv-shows
└── [index].js
Paste this into the file [index].js
import { useRouter } from "next/router";
export async function getStaticPaths() {
return {
paths: [{ params: { index: "0" } }, { params: { index: "1" } }],
fallback: false
};
}
export async function getStaticProps(context) {
const MY_PLAYLIST_1 = "PL9562CjMJkXIgaV_UA5hf1VADfn4Sqd0P";
const MY_PLAYLIST_2 = "PL9562CjMJkXIgaV_UA5hf1VADfn4Sqd0P";
const API_KEY = "AIzaSyCELe0KoZYBjonJskBMbzdlTuCow3sr3zo";
const PLAYLIST_REQUEST_URL_1 = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=500&playlistId=${MY_PLAYLIST_1}&key=${API_KEY}`;
const PLAYLIST_REQUEST_URL_2 = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=500&playlistId=${MY_PLAYLIST_2}&key=${API_KEY}`;
const playlistResponse1 = await fetch(PLAYLIST_REQUEST_URL_1);
const playlistResponse2 = await fetch(PLAYLIST_REQUEST_URL_2);
const playlistResult1 = await playlistResponse1.json();
const playlistResult2 = await playlistResponse2.json();
return {
props: {
results: [playlistResult1, playlistResult2],
},
revalidate: 3600,
};
}
export default function TvShows({results}) {
const router = useRouter();
const { index } = router.query;
return <div>{index}, {JSON.stringify(results[index])}</div>;
}
Next step, override content of card.js with the following (just remove result variable and the query parameter)
import Link from "next/link";
const Card = ({ index }) => {
return (
<nav>
<Link
href={`/tv-shows/${index}`}
>
<div>
<h1>card click</h1>
</div>
</Link>
</nav>
);
};
export default Card;
Override index.js to remove unnecessary API calling code and take new card.js's props into account:
import Link from "next/link";
import Card from "../comps/card";
import Popular from "../comps/popular";
export default function IndexPage() {
return (
<div>
Hello World. {/* <Link href="/about">
<a>About</a>
</Link> */}
<Card index={0} img={Popular[0].img} />
<Card index={1} img={Popular[1].img} />
</div>
);
}
How the solution works is as follows:
We create dynamic routes which takes only query parameter index of our playlist. Every index parameter that is possible to be set is defined in paths: [{ params: { index: "0" } }, { params: { index: "1" } }]. These path params are then passed to our dynamic route which is then pre-rendered, and downloading all the data only once. And finally, our route displays data based on query parameters supplied by useRouter.
I have done a lot of research and tried many things, but unfortunately, I haven't found a solution, so I had to ask again.
I am working locally on a project and now I want to add Internationalized Routing from nextjs to my project so that I can offer it in 2 languages... I read the documentation of nextjs and watched youtube tutorials and tried but it always comes back in locale:undefined and unfortunately I don't know why?
below you can see my codes... Can you maybe tell me what I am not doing right? or what I am doing wrong?
index.tsx
export default function Home({ posts }: Props) {
const router = useRouter()
const t = router.locale === 'de' ? de : tr
console.log(router)
return (
<Header />
<main className="flex w-full flex-1 flex-col items-center justify-center px-20 text-center">
<h1 className="text-6xl font-bold">
{t.title}
<a className="text-blue-600" href="https://nextjs.org">
Next.js!
</a>
</h1>
<div>
<Link href="/" locale="de">
<a>DE </a>
</Link>
<Link href="/tr" locale="tr">
<a>TR</a>
</Link>
</div>
)
next.config.js
/** #type {import('next').NextConfig} */
module.exports = {
reactStrictMode: true,
i18n: {
locales: ['de', 'tr'],
defaultLocale: 'de',
},
}
locales/de.js
export const de = {
title: 'Welcome to ',
}
Try this
export default function Home({ posts }: Props) {
const router = useRouter()
let t = "";
useEffect(()=>{
t = router.locale === 'de' ? de : tr
},[]);
return (
</>
Your Other Code ...
</>
)
I keep having errors trying to deploy my Nextjs app to vercel:
Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: (0 , react_development_.useState) is not a function or its return value is not iterable
at Categories (/vercel/path0/.next/server/chunks/930.js:122:72)
at d (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:33:498)
at bb (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:16)
at a.b.render (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:42:43)
at a.b.read (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:41:83)
at Object.exports.renderToString (/vercel/path0/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:52:138)
at Object.renderPage (/vercel/path0/node_modules/next/dist/server/render.js:686:46)
at Object.defaultGetInitialProps (/vercel/path0/node_modules/next/dist/server/render.js:316:51)
at Function.getInitialProps (/vercel/path0/.next/server/pages/_document.js:514:20)
at Object.loadGetInitialProps (/vercel/path0/node_modules/next/dist/shared/lib/utils.js:69:29)
I tried npm run build locally and I get this error:
> Build error occurred
Error: Export encountered errors on following paths:
/
/post/[slug]: /post/first-post
/post/[slug]: /post/how-html-css-js-work
/post/[slug]: /post/nextjs
/post/[slug]: /post/react-hooks
So I assume it has to be something inside my index page and /post/[slug] page. I tried everything like setting getStaticPaths fallback to false and using optional chaining everywhere but I still get the error.
Can someome please help me out, it is so depressing when I finished the project and I can run it in my localhost but and failed in the deployment/build time.
My / page:
import Head from "next/head";
import { PostCard, Categories, PostWidget } from "../components";
import { getPosts } from "../services";
export default function Home({ posts }) {
const sortedPosts = posts.sort(
(a, b) => new Date(b.node.createdAt) - new Date(a.node.createdAt)
);
return (
<>
<Head>
<title>JBLOG | Home</title>
</Head>
<section className="bg-zinc-200 dark:bg-gray-500 transition-colors px-5">
<div className="max-w-7xl mx-auto py-10">
<div className="grid grid-cols-1 md:grid-cols-12 gap-12">
<div className="md:col-span-8 col-span-1 ">
{sortedPosts?.map((post) => (
<PostCard key={post.node.title} post={post.node} />
))}
</div>
<div className="md:col-span-4 col-span-1">
<div className="md:sticky relative md:top-[110px]">
<PostWidget />
<Categories />
</div>
</div>
</div>
</div>
</section>
</>
);
}
export async function getStaticProps() {
const posts = (await getPosts()) || [];
return {
props: {
posts,
},
};
}
My /post/slug page:
import React from "react";
import Head from "next/head";
import { getPosts, getPostDetails } from "../../services";
import {
PostDetail,
Categories,
PostWidget,
Author,
Comments,
CommentsForm,
} from "../../components";
import { useRouter } from "next/router";
const Post = ({ post }) => {
const router = useRouter();
if (router.isFallback) {
return <div>Loading...</div>;
}
return (
<>
<Head>
<title>{post?.title}</title>
</Head>
<section className="bg-zinc-200 dark:bg-gray-500 transition-colors px-5">
<div className="max-w-7xl mx-auto py-10">
<div className="grid grid-cols-1 md:grid-cols-12 md:gap-6">
<div className="md:col-span-8 col-span-1 ">
<PostDetail post={post} />
<CommentsForm slug={post?.slug} />
<Comments slug={post?.slug} />
</div>
<div className="md:col-span-4 col-span-1">
<div className="md:sticky relative md:top-[110px]">
<Author author={post?.author} />
<PostWidget
slug={post?.slug}
categories={post?.categories?.map(
(category) => category.slug
)}
/>
<Categories />
</div>
</div>
</div>
</div>
</section>
</>
);
};
export default Post;
export const getStaticProps = async (context) => {
const data = await getPostDetails(context.params.slug);
return {
props: {
post: data,
},
};
};
export const getStaticPaths = async () => {
const posts = await getPosts();
return {
paths: posts.map((post) => ({ params: { slug: post.node.slug } })),
fallback: true,
};
};
what's your npm run build?
https://nextjs.org/docs/basic-features/data-fetching
fallback: true is not supported when using next export.
I'm using a 3rd party API https://www.metaweather.com and in my package.json i've added
"proxy": "https://www.metaweather.com",
My app.js is as follows:
import { createContext, useState } from "react";
import LocationSearch from "./components/locationSearch";
import MainWeather from "./components/mainWeather";
import ExtraWeather from "./components/ExtraWeather";
export const DisplayContext = createContext({
display: false,
setDisplay: () => {},
});
function App() {
const [woeid, setWoeid] = useState(null);
const [display, setDisplay] = useState(false);
return (
<DisplayContext.Provider value={{ display, setDisplay }}>
<LocationSearch setWoeid={setWoeid} />
<MainWeather woeid={woeid} />
<ExtraWeather />
</DisplayContext.Provider>
);
}
export default App;
my LocationSearch.jsx:
import React, { useContext, useState } from "react";
import axios from "axios";
import { DisplayContext } from "../App";
const LocationSearch = ({ setWoeid }) => {
const [data, setData] = useState({
location: "",
});
const { setDisplay } = useContext(DisplayContext);
function submit(e) {
e.preventDefault();
axios
.get(
// "https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/search/?query=" +
"/api/location/search/?query=" +
data.location,
{
location: data.location,
}
)
.then((res) => {
console.log(res.data[0].woeid);
setWoeid(res.data[0].woeid);
setTimeout(() => setDisplay(true), 5000);
})
.catch((err) => {
console.log(err);
});
}
function handle(e) {
const newdata = { ...data };
newdata[e.target.id] = e.target.value;
setData(newdata);
console.log(newdata);
}
return (
<div className="flex w-96 mx-auto mt-5 p-3 rounded-xl bg-blue-300">
<form className="flex w-96 mx-auto p-3 rounded-xl bg-white">
<div>
<input
className="text-gray-700"
onChange={(e) => handle(e)}
id="location"
value={data.location}
placeholder="Search for location"
type="text"
/>
<button
className="bg-blue-900 text-gray-300 py-3 px-5 ml-12 rounded-xl"
type="submit"
onClick={(e) => submit(e)}
>
Search
</button>
</div>
</form>
</div>
);
};
export default LocationSearch;
my MainWeather.jsx:
import React, { useContext, useEffect, useState } from "react";
import axios from "axios";
import { DisplayContext } from "../App";
import Loader from "react-loader-spinner";
const MainWeather = ({ woeid }) => {
const [temp, setTemp] = useState([]);
const [icon, setIcon] = useState("");
const { display } = useContext(DisplayContext);
const [load, setLoad] = useState(false);
useEffect(() => {
axios
.get(
// "https://cors-anywhere.herokuapp.com/https://www.metaweather.com/api/location/" +
"/api/location/" +
woeid
)
.then((res) => {
setLoad(true);
console.log(res.data[0]);
setIcon(res.data.consolidated_weather[0].weather_state_abbr);
setTemp((prev) => {
return [
...prev,
res.data.consolidated_weather[0].the_temp,
res.data.consolidated_weather[0].min_temp,
res.data.consolidated_weather[0].max_temp,
res.data.consolidated_weather[0].weather_state_name,
];
});
})
.catch((err) => {
console.log(err);
});
}, [woeid]);
return (
<>
{display && (
<div className="w-96 flex flex-col mx-auto p-3 mt-2 rounded-xl bg-blue-300">
<img
src={"/static/img/weather/" + icon + ".svg"}
alt="Current weather icon"
className="w-40 mx-auto pb-4"
/>
<p className="mx-auto text-5xl pb-3">{Math.round(temp[0])}°C</p>
<p className="mx-auto pb-1">
{Math.round(temp[1])} / {Math.round(temp[2])}
</p>
<p className="mx-auto pb-2">{temp[3]}</p>
</div>
)}
{!display && (
<div>
{load && (
<div className="flex w-96 h-80 mx-auto mt-5 p-3 rounded-xl bg-blue-300">
<Loader
className="m-auto"
type="Puff"
color="#00BFFF"
height={100}
width={100}
timeout={5000}
/>
</div>
)}
{!load && (
<div className="flex w-96 h-80 mx-auto mt-5 p-3 rounded-xl bg-blue-300">
<h1 className="m-auto">Please enter a location</h1>
</div>
)}
</div>
)}
</>
);
};
export default MainWeather;
The ExtraWeather.jsx isn't relevant.
If I comment out the MainWeather and log the return from the LocationSearch it returns to object perfectly but as soon as I introduce the MainWeather back I get "CORS header ‘Access-Control-Allow-Origin’ missing" error. I've tried everything I can find from hosting the app on Netlify, changing what is the proxy to the local host address, moving things to different places, and I'm unsure if I did it correctly but I did try a reverse proxy.
Also using herokuapp and a browser extension does fix the problem but I want something more permanent.
Any help will be greatly appreciated.
The issue is that the response is being redirected to include a / suffix, ie
HTTP/2 301
location: https://www.metaweather.com/api/location/44418/
This causes your browser to re-attempt the request to that URL which bypasses your proxy.
Try including the / suffix, eg
axios.get(`/api/location/${woeid}/`)
Keep in mind that the proxy setting only works for local development. If you're deploying to Netlify, see https://docs.netlify.com/routing/redirects/rewrites-proxies/#proxy-to-another-service
Debugging Process
Something was directing your browser to try and access the API by its full URL so I suspected a redirect.
I just ran
curl -v "https://www.metaweather.com/api/location/44418" -o /dev/null
and looked at the response status and headers...
> GET /api/location/44418 HTTP/2
> Host: www.metaweather.com
< HTTP/2 301
< location: https://www.metaweather.com/api/location/44418/
Spotting the difference was the hard part 😄
You could probably have seen something similar in your browser dev-tools Network panel; first a request to /api/location/44418 with a 301 response and location header, then a request to https://www.metaweather.com/api/location/44418/ which failed CORS checks