Home  >  Q&A  >  body text

Dynamic metadata configuration of Next.js application directory to match status values

In the app directory of Next.js 13, I saw in the official documentation that they have abandoned the old head method in favor of metadata, I think it Can only be used on pages or layouts.

I want to change the title based on the status value, how can I do it? The object in the metadata is outside the component, so I can't reference it.

import type { Metadata } from 'next';
 
export const metadata: Metadata = {
  title: 'Home',
  description: 'Welcome to Next.js',
};
 
export default function Page() {
  return '...';
}


P粉713866425P粉713866425318 days ago455

reply all(1)I'll reply

  • P粉025632437

    P粉0256324372023-12-29 09:25:09

    If by "state" you mean something similar to "useState", then this is not possible. Because metadata only applies to server components, and useState can only be used in client components. Documentation says :

    For normal pages, you usually know what metadata you want to return, so a metadata object should be sufficient. If the page is dynamic, there is generateMetadata :

    The following is an example of dynamically setting the title:

    // app/products/[id]/page.tsx
    
    export async function generateMetadata({ params, searchParams }) {
      // read route params
      const id = params.id;
    
      // fetch data
      const product = await fetch(`/api/products/${id}`).then((res) => res.json());
    
      // return a dynamic title
      return {
        title: product.title,
      };
    }
    
    export default function Page() {
      return '...';
    }
    

    reply
    0
  • Cancelreply