Page with server components
- React course
- Expert
- Lesson 27/32
- 5 min
Write a page that fetches data with a server component.
Page with server components
In the third step you will write a server component page. ProductPage is an async function that fetches products with await fetch.
The starting code includes the Button and ThemeProvider solutions; so the design system and theme are ready. The page renders on the server and reaches the client as HTML.
Products are listed inside a <ul>; each tracked by a key.
Combining with client components
Data is passed from a server component to a client component as props. For example <Button variant="primary">Buy</Button> is a client component; but it can be used inside ProductPage.
This split keeps data fetching on the server and interaction on the client. The bundle stays small and the first render fast.
A client component can also be passed as children.
Practice Write the ProductPage server component
Write a ProductPage server component. async function ProductPage(). Fetch with await fetch('/api/products') and parse with res.json(). Inside a <main> show <h1>Products</h1> and inside a <ul> map products to <li key={p.id}>{p.name}</li>. Export it.
Starter code
// Button.jsx
function Button({ variant, children }) {
const className = variant === 'primary' ? 'btn-primary' : 'btn-secondary';
return <button className={className}>{children}</button>;
}
export default Button;
// ThemeProvider.jsx
import { createContext, useState } from 'react';
const ThemeContext = createContext();
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export default ThemeProvider;
// ProductPage.jsx
// Write the ProductPage server component hereSample solution
async function ProductPage() {
const res = await fetch('/api/products');
const products = await res.json();
return (
<main>
<h1>Products</h1>
<ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>
</main>
);
}
export default ProductPage;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match server component concepts
| Term | Meaning |
|---|---|
async function |
Fetches on server |
await fetch |
Waits for data |
res.json |
Parse to JSON |
products.map |
Render the list |
2 What kind of component is ProductPage?
- Client component
- Edge component
- Shared component
- Server component (async) Correct answer
Explanation: ProductPage is an async server component.
3 Fill in the blank: list the products
<ul>{products.map(p => <li ____={p.id}>{p.name}</li>)}</ul>
<ul>{products.map(p => <li key={p.id}>{p.name}</li>)}</ul>
Explanation: List items are tracked by key.