Create the Server Component in the next js

File Structure

/app
 /articles
  /[id]
   page.jsx
  page.jsx
 layout.js
 page.js

Fetching Articles with a Server Component

// app/articles/page.jsx
async function getArticles() {
 // Simulate fetching data from an API
 const articles = [
  { id: 1, title: "Introduction to Next.js 13", content: "Learn about the new App Router..." },
  { id: 2, title: "React Server Components", content: "RSC allows you to fetch data server-side..." },
 ];
 return articles;
}

export default async function ArticlesPage() {
 const articles = await getArticles();

 return (
  <div>
   <h2>Articles</h2>
   <ul>
    {articles.map((article) => (
     <li key={article.id}>
      <a href={`/articles/${article.id}`}>{article.title}</a>
     </li>
    ))}
   </ul>
  </div>
 );
}

Creating an Article Detail Page 

// app/articles/[id]/page.jsx
async function getArticle(id) {
  // Simulate fetching a single article by ID
  const articles = [
    { id: 1, title: "Introduction to Next.js 13", content: "Learn about the new App Router..." },
    { id: 2, title: "React Server Components", content: "RSC allows you to fetch data server-side..." },
  ];
  return articles.find((article) => article.id === parseInt(id));
}


export default async function ArticlePage({ params }) {
  const article = await getArticle(params.id);


  if (!article) {
    return <p>Article not found</p>;
  }


  return (
    <div>
      <h2>{article.title}</h2>
      <p>{article.content}</p>
      <a href="/articles">Back to articles</a>
    </div>
  );
}


Leave a comment

Your email address will not be published. Required fields are marked *