skip to Main Content

before next js 13 we used to do dynamic head as an import. but in Next JS 13 they introduced the head.js class. this works when using a static page, but when loading a dynamic how can we change the title and desc in the head? i directly imported the next/head and then assign the data but it didn’t change the head.

export default function DetailPage({ params: { itemid } }) {

const [datas, setDatas] = useState({});

  const getData = async () => {
    const docRef = doc(db, "items", itemid);
    const docSnap = await getDoc(docRef);
    setDatas(docSnap.data());
  };

  useEffect(() => {
    if (Object.keys(datas).length == 0) {
      getData();
    }
  }, [datas]);

return (

<>
<Head>
        <title>{datas.title}</title>
        <meta name="viewport" content="initial-scale=1.0, width=device-width" />
        <meta
          name="keywords"
          content="some contents"
        />
        <meta
          name="description"
          content={datas.desc}
        />
      </Head>

  <section>...</section>

</>

)

}

2

Answers


  1. I am guessing you are using the app directory, the Head component has been replaced by the generateMetadata API. Usage could use something like this inside your page:

    import type { Metadata } from "next";
    
    export function MyPage(): Promise<JSX.Element> {
      return <></>;
    }
    
    export async function generateMetadata(): Promise<Metadata> {
      const data = await getMyData();
      return {
        // return your metadata here
      };
    }
    

    You can find a full API reference and a method for static metadata inside the official docs.

    Login or Signup to reply.
  2. import React from 'react'
    
    export const metadata = {
        title: 'About Page',
        description:
          'About Page',
      };
    
    const About = () => {
      return (
        <>
            <h1>About Page</h1>
        </>
      )
    }
    
    export default About
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search