경계를 넘는 props는 서버 컴포넌트가 클라이언트 컴포넌트에 넘기는 props입니다. 이 값은 글로 바뀌어 쪽과 함께 브라우저로 가므로, 글로 바꿀 수 있는 값이어야 합니다. 이 레슨은 별 단추에 레시피 객체를 넘기고, 함수를 넘기면 나는 오류를 본 뒤, 재료 목록을 children으로 끼우는 재료 접기 Fold를 만듭니다.
지금 별은 넷 다 ☆로 시작합니다. lib/recipes.ts의 김치볶음밥과 바나나 팬케이크는 favorite: true인데, 별 단추가 레시피를 모르기 때문입니다.
JS 다시 보기: JSON.stringify는 객체를 글로 바꾸며, 함수인 속성은 말없이 뺐습니다(JSON: 객체와 글 사이). React 다시 보기: 여는 태그와 닫는 태그 사이에 넣은 JSX는 children으로 받고, 그 타입은 ReactNode입니다(props와 children에 타입).
1레시피 객체 넘기기
개발 서버는 켜 둔 채 따라 합니다. 별 단추가 recipe를 받아, 별의 처음 값을 recipe.favorite으로 둡니다. Recipe는 타입만 쓰므로 import type으로 가져옵니다. import type 줄은 실행 전에 지워지므로(리액트를 TS로), 별 단추가 lib/recipes.ts를 경계 아래로 끌고 오지 않습니다. 규칙 4가 끌고 가는 것은 실행할 때 쓰는 import입니다.
'use client';
import {
useState,
} from 'react';
import type {
Recipe,
} from '@/lib/recipes';
function FavoriteButton({
recipe,
}: {
recipe: Recipe;
}) {함수 몸을 이어 씁니다.
const [starred, setStarred] =
useState(recipe.favorite);
function handleClick() {
setStarred(!starred);
}
return (
<button
onClick={handleClick}
>
{starred ? '★' : '☆'}
</button>
);
}
export default FavoriteButton;목록 쪽은 항목마다 그 레시피를 넘깁니다(…는 앞 레슨 그대로인 줄).
…
<FavoriteButton
recipe={r}
/>
…저장하고 /recipes를 새로 고치면 김치볶음밥과 바나나 팬케이크의 별이 ★로 섭니다. 받은 HTML에서도 ★입니다. 서버가 별 단추를 그릴 때 recipe.favorite을 읽었습니다.
app/recipes/page.tsx 전체 · 받은 HTML(다듬음)
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
recipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
export default function Page() {
return (
<ul>{recipes.map(item)}</ul>
);
}<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<ul>
<li>
<a href="/recipes/r1">김치볶음밥</a>
<button>★</button>
</li>
<li>
<a href="/recipes/r2">토마토 파스타</a>
<button>☆</button>
</li>
<li>
<a href="/recipes/r3">계란말이</a>
<button>☆</button>
</li>
<li>
<a href="/recipes/r4">바나나 팬케이크</a>
<button>★</button>
</li>
</ul>
</section>
<footer>바닥글</footer>브라우저도 같은 값을 알아야 합니다. 하이드레이션 때 별 단추를 다시 부르는데, 두 번 그린 결과가 같아야 하니까요(규칙 5). 그래서 넘긴 recipe 객체는 글로 바뀌어 쪽과 함께 갑니다. 페이지 소스에서 밀가루를 찾으면 <script> 안에서 한 번 나옵니다. 바나나 팬케이크 객체의 재료 배열이 글로 실린 자리입니다. 앞 레슨 끝 판의 페이지 소스에는 밀가루가 없었습니다.
Next.js 규칙 4 넓힘. 경계를 넘는 props는 글로 바꿀 수 있는 값이어야 합니다. 글 · 수 · 참거짓과 그것을 담은 배열 · 객체는 넘어갑니다.
별은 여전히 화면에서만 바뀝니다. 김치볶음밥의 별을 눌러 ☆로 바꾸고 새로 고치면 다시 ★입니다. recipe.favorite이 그대로이기 때문이고, 별을 저장하는 것은 단원 9입니다.
해 보기 — 함수를 넘기면
별 곁에 조리 시간을 15분처럼 적어 보려 합니다. 목록 쪽에 글을 만드는 함수 format을 두고, 별 단추에 넘겨 부르게 합니다(…는 1절 그대로인 줄).
…
function FavoriteButton({
recipe,
format,
}: {
recipe: Recipe;
format: (r: Recipe) => string;
}) {
…
{starred ? '★' : '☆'}
{format(recipe)}
</button>
……
function format(r: Recipe) {
return r.minutes + '분';
}
…
<FavoriteButton
recipe={r}
format={format}
/>
…저장하고 쪽을 새로 고치면 쪽이 500으로 멈춥니다. 서버 터미널에는 같은 오류 덩어리가 여러 번 찍힙니다. 첫 덩어리만 읽습니다.
- 첫 줄 —
⨯ Error: Functions cannot로 시작해be passed directly to와Client Components로 이어진다. 함수는 클라이언트 컴포넌트에 바로 넘길 수 없다 - 둘째 줄 —
<... recipe={{...}}다음format={function format}, 그 아래^^^가 넘긴 함수 자리를 가리킨다
함수는 글로 바꿀 수 없어, 브라우저의 별 단추에 건넬 길이 없습니다. JSON.stringify처럼 말없이 빼지도 않고 쪽을 멈춥니다. 첫 줄 가운데 marking it with "use server"는 'use server'로 표시한 함수, 곧 서버 함수만은 넘길 수 있다는 말입니다. 서버 함수는 단원 6에서 씁니다. 끝의 Or maybe you meant로 시작하는 문장은 함수를 넘기지 말고 불러서 그 결과를 넘기려던 것 아니냐고 묻습니다.
고친 파일 둘 · 응답 머리 · 서버 터미널
'use client';
import {
useState,
} from 'react';
import type {
Recipe,
} from '@/lib/recipes';
function FavoriteButton({
recipe,
format,
}: {
recipe: Recipe;
format: (r: Recipe) => string;
}) {
const [starred, setStarred] =
useState(recipe.favorite);
function handleClick() {
setStarred(!starred);
}
return (
<button
onClick={handleClick}
>
{starred ? '★' : '☆'}
{format(recipe)}
</button>
);
}
export default FavoriteButton;import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
recipes,
type Recipe,
} from '@/lib/recipes';
function format(r: Recipe) {
return r.minutes + '분';
}
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
format={format}
/>
</li>
);
export default function Page() {
return (
<ul>{recipes.map(item)}</ul>
);
}HTTP/1.1 500 Internal Server Error
Cache-Control: no-store
Content-Type: text/html; charset=utf-8
> recipe-box-next@0.1.0 dev
> next dev
▲ Next.js 16.4.6 (Turbopack)
- Local: http://localhost:3000
- Network: http://127.131.113.34:3000
✓ Ready in 210ms
✓ Running next.config.ts took 991ms
- Cache Components enabled
- Partial Prefetching enabled
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
<... recipe={{...}} format={function format}>
^^^^^^^^^^^^^^^^^
at ignore-listed frames {
digest: '1115005172'
}
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
<... recipe={{...}} format={function format}>
^^^^^^^^^^^^^^^^^
at ignore-listed frames {
digest: '1115005172'
}
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
<... recipe={{...}} format={function format}>
^^^^^^^^^^^^^^^^^
at ignore-listed frames {
digest: '1115005172'
}
⨯ Error: Functions cannot be passed directly to Client Components unless you explicitly expose it by marking it with "use server". Or maybe you meant to call this function rather than return it.
<... recipe={{...}} format={function format}>
^^^^^^^^^^^^^^^^^
at ignore-listed frames {
digest: '1115005172'
}
GET /recipes 500 in 319ms (next.js: 49ms, application-code: 270ms)
다 봤으면 format을 지워 1절 판으로 되돌립니다.
2재료 목록을 children으로 끼우기
자세히 쪽에 재료 목록을 접었다 펴는 Fold를 둡니다. 펴고 접는 state가 있으니 'use client' 파일이고, 펼칠 내용은 children으로 받습니다. 어디서 도는지 보려고 함수 맨 앞에 로그를 둡니다. 새 파일이라 아래 접기의 전체 파일을 옮겨 칩니다(조각의 …는 줄인 줄).
'use client';
…
function Fold({
children,
}: {
children: ReactNode;
}) {
console.log('Fold를 부름');
…
{open && children}
…자세히 쪽에는 재료 배열을 <ul>로 그리는 서버 컴포넌트 Ingredients를 같은 파일에 두고(로그 재료 목록을 부름), Fold의 여는 태그와 닫는 태그 사이에 끼웁니다.
…
const items =
found.ingredients;
return (
<>
<h2>{found.title}</h2>
<Fold>
<Ingredients
items={items}
/>
</Fold>
</>
);
…/recipes/r1을 열고 '재료 보기'를 누르면 밥 · 김치 · 달걀이 펼쳐집니다. 아래 접기에는 두 파일 전체와, 연 뒤의 서버 터미널 · 브라우저 콘솔, 누른 뒤 화면에 보이는 <body> 안 HTML · 콘솔을 실었습니다.
두 파일 전체 · 터미널 · 콘솔 · 누른 뒤 화면 · 콘솔
'use client';
import {
useState,
type ReactNode,
} from 'react';
function Fold({
children,
}: {
children: ReactNode;
}) {
console.log('Fold를 부름');
const [open, setOpen] =
useState(false);
const label = open
? '재료 접기'
: '재료 보기';
function handleClick() {
setOpen(!open);
}
return (
<section>
<button
onClick={handleClick}
>
{label}
</button>
{open && children}
</section>
);
}
export default Fold;import {
notFound,
} from 'next/navigation';
import {
recipes,
} from '@/lib/recipes';
import Fold from
'@/components/Fold';
export const
generateStaticParams = () =>
recipes.map((r) => ({
id: r.id,
}));
function Ingredients({
items,
}: {
items: string[];
}) {
console.log('재료 목록을 부름');
return (
<ul>
{items.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
);
}
async function Page({
params,
}: PageProps<'/recipes/[id]'>) {
const { id } = await params;
const found = recipes.find(
(r) => r.id === id,
);
if (!found) {
notFound();
}
const items =
found.ingredients;
return (
<>
<h2>{found.title}</h2>
<Fold>
<Ingredients
items={items}
/>
</Fold>
</>
);
}
export default Page;> recipe-box-next@0.1.0 dev
> next dev
▲ Next.js 16.4.6 (Turbopack)
- Local: http://localhost:3000
- Network: http://127.131.113.34:3000
✓ Ready in 209ms
✓ Running next.config.ts took 989ms
- Cache Components enabled
- Partial Prefetching enabled
재료 목록을 부름
Fold를 부름
GET /recipes/r1 200 in 569ms (next.js: 54ms, generate-params: 435ms, application-code: 79ms)
재료 목록을 부름
Fold를 부름
Fold를 부름
Fold를 부름
Fold를 부름
Fold를 부름
Error: Route "/recipes/[id]": Next.js encountered URL data during prerendering or a navigation.
`params` or `searchParams` accessed outside of `<Suspense>` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
at Page (app/recipes/[id]/page.tsx:34:18)
32 | params,
33 | }: PageProps<'/recipes/[id]'>) {
> 34 | const { id } = await params;
| ^
35 | const found = recipes.find(
36 | (r) => r.id === id,
37 | );
[Prerender] 재료 목록을 부름
Fold를 부름
Fold를 부름
[오류] Error: Route "/recipes/[id]": Next.js encountered URL data during prerendering or a navigation.
`params` or `searchParams` accessed outside of `<Suspense>` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<h2>김치볶음밥</h2>
<section>
<button>재료 접기</button>
<ul>
<li>밥</li>
<li>김치</li>
<li>달걀</li>
</ul>
</section>
</section>
<footer>바닥글</footer>[Prerender] 재료 목록을 부름
Fold를 부름
Fold를 부름
[오류] Error: Route "/recipes/[id]": Next.js encountered URL data during prerendering or a navigation.
`params` or `searchParams` accessed outside of `<Suspense>` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
Fold를 부름
Fold를 부름
서버 터미널에는 요청 때 재료 목록을 부름과 Fold를 부름이 찍힙니다. 브라우저 콘솔에는 Fold를 부름이 두 번(개발 판의 두 번 부르기)이고, 재료 목록은 [Prerender] 꼬리표를 단 한 줄뿐입니다. 서버에서 찍은 로그를 다시 보여 준 줄입니다. '재료 보기'를 누르면 Fold를 부름만 더 찍힙니다. 터미널과 콘솔에서 encountered URL data가 든 Error: Route 덩어리는 동적 경로 [id]에서 본 알림입니다.
Fold는 클라이언트 컴포넌트지만, 그 안에 끼운 Ingredients는 Page와 같은 파일에 둔 서버 컴포넌트라 서버에서 그립니다. 경계를 넘는 것은 그린 결과뿐입니다. Next.js 문서도 children으로 넘긴 서버 컴포넌트를 이렇게 적습니다. 'They are rendered on the server and passed to the Client Component as rendered output.'(서버에서 그려, 그린 결과로 클라이언트 컴포넌트에 넘어간다)
해 보기 — Fold가 재료 목록을 import 하면
이번에는 Fold가 재료 목록을 직접 그리게 합니다. Ingredients를 components/Ingredients.tsx로 옮기고('use client' 줄 없이), Fold는 그것을 import 해 재료 배열 items만 받습니다. 쪽은 <Fold items={items} />로 바꿉니다. 콘솔에서 재료 목록 줄이 눈에 띄게 Fold의 로그 줄은 지웁니다.
…
import Ingredients from
'@/components/Ingredients';
function Fold({
items,
}: {
items: string[];
}) {
…
{open && (
<Ingredients
items={items}
/>
)}
…'재료 보기'를 누르면 재료 목록을 부름은 어디에 찍힐까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ① 서버 터미널 —
Ingredients.tsx에는'use client'가 없으니 - ② 브라우저 콘솔
- ③ 아무 데도 — 클라이언트 파일은 서버 컴포넌트 파일을 import 할 수 없어 오류가 난다
결과 보기
②입니다. 아래는 세 파일(Fold의 로그 줄은 지움)과, 열어서 '재료 보기'를 누른 뒤의 브라우저 콘솔 · 서버 터미널입니다.
function Ingredients({
items,
}: {
items: string[];
}) {
console.log('재료 목록을 부름');
return (
<ul>
{items.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
);
}
export default Ingredients;'use client';
import {
useState,
} from 'react';
import Ingredients from
'@/components/Ingredients';
function Fold({
items,
}: {
items: string[];
}) {
const [open, setOpen] =
useState(false);
const label = open
? '재료 접기'
: '재료 보기';
function handleClick() {
setOpen(!open);
}
return (
<section>
<button
onClick={handleClick}
>
{label}
</button>
{open && (
<Ingredients
items={items}
/>
)}
</section>
);
}
export default Fold;import {
notFound,
} from 'next/navigation';
import {
recipes,
} from '@/lib/recipes';
import Fold from
'@/components/Fold';
export const
generateStaticParams = () =>
recipes.map((r) => ({
id: r.id,
}));
async function Page({
params,
}: PageProps<'/recipes/[id]'>) {
const { id } = await params;
const found = recipes.find(
(r) => r.id === id,
);
if (!found) {
notFound();
}
const items =
found.ingredients;
return (
<>
<h2>{found.title}</h2>
<Fold items={items} />
</>
);
}
export default Page;[오류] Error: Route "/recipes/[id]": Next.js encountered URL data during prerendering or a navigation.
`params` or `searchParams` accessed outside of `<Suspense>` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
재료 목록을 부름
재료 목록을 부름
> recipe-box-next@0.1.0 dev
> next dev
▲ Next.js 16.4.6 (Turbopack)
- Local: http://localhost:3000
- Network: http://127.131.113.34:3000
✓ Ready in 207ms
✓ Running next.config.ts took 1002ms
- Cache Components enabled
- Partial Prefetching enabled
GET /recipes/r1 200 in 275ms (next.js: 52ms, generate-params: 139ms, application-code: 83ms)
Error: Route "/recipes/[id]": Next.js encountered URL data during prerendering or a navigation.
`params` or `searchParams` accessed outside of `<Suspense>` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with `<Suspense fallback={...}>` around the data access
- [block] Set `export const instant = false` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
at Page (app/recipes/[id]/page.tsx:19:18)
17 | params,
18 | }: PageProps<'/recipes/[id]'>) {
> 19 | const { id } = await params;
| ^
20 | const found = recipes.find(
21 | (r) => r.id === id,
22 | );
누른 뒤 재료 목록을 부름은 브라우저 콘솔에 [Prerender] 없이 찍힙니다. 'use client' 파일이 import 한 것은 그 줄이 없어도 클라이언트 쪽으로 끌려가, 누를 때 브라우저가 부릅니다(규칙 4 — ①이 아님). 오류도 아닙니다. 끌려간 Ingredients가 클라이언트 컴포넌트가 될 뿐입니다(③이 아님).
터미널에 없는 것은 쪽을 처음 그릴 때 Fold가 접혀 있어, 서버가 Ingredients를 그리지 않았기 때문입니다. Fold의 처음 값을 useState(true)로 두어 펼친 채 시작하면, 새로 고칠 때 서버 터미널에도 찍히고 받은 HTML에 목록이 듭니다. 쪽을 새로 고칠 때 그려지는 클라이언트 컴포넌트는 서버에서도 한 번 불립니다('use client' 경계).
같은 Ingredients도 Page와 같은 파일에 두고 children으로 끼우면 서버 쪽에, Fold가 import 하면 클라이언트 쪽에 섭니다.
다 봤으면 components/Ingredients.tsx를 지우고 2절 판으로 되돌립니다.
예제
로그 두 줄을 지워 이 레슨의 끝 판으로 정리하고 /recipes/r1을 다시 엽니다. 아직 '재료 보기'를 누르지 않았을 때, 페이지 소스에 재료 달걀이 있을까요? 고른 뒤 펼쳐 보세요. 맞혀 보기는 점수에 들지 않습니다.
- ① 없다 — 접혀 있어 그리지 않았으니
- ② 있다
- ③ 없다 — 누를 때 서버에서 받아 오니
결과 보기
②입니다. 아래는 로그를 지운 두 파일과, 받은 HTML(다듬음) · 누른 뒤 화면에 보이는 <body> 안 HTML입니다.
'use client';
import {
useState,
type ReactNode,
} from 'react';
function Fold({
children,
}: {
children: ReactNode;
}) {
const [open, setOpen] =
useState(false);
const label = open
? '재료 접기'
: '재료 보기';
function handleClick() {
setOpen(!open);
}
return (
<section>
<button
onClick={handleClick}
>
{label}
</button>
{open && children}
</section>
);
}
export default Fold;import {
notFound,
} from 'next/navigation';
import {
recipes,
} from '@/lib/recipes';
import Fold from
'@/components/Fold';
export const
generateStaticParams = () =>
recipes.map((r) => ({
id: r.id,
}));
function Ingredients({
items,
}: {
items: string[];
}) {
return (
<ul>
{items.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
);
}
async function Page({
params,
}: PageProps<'/recipes/[id]'>) {
const { id } = await params;
const found = recipes.find(
(r) => r.id === id,
);
if (!found) {
notFound();
}
const items =
found.ingredients;
return (
<>
<h2>{found.title}</h2>
<Fold>
<Ingredients
items={items}
/>
</Fold>
</>
);
}
export default Page;<nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<h2>김치볶음밥</h2>
<section>
<button>재료 보기</button>
</section>
</section>
<footer>바닥글</footer><nav><a href="/recipes">▸ 목록</a>·<a href="/stats">통계</a></nav>
<section>
<h1>레시피</h1>
<h2>김치볶음밥</h2>
<section>
<button>재료 접기</button>
<ul>
<li>밥</li>
<li>김치</li>
<li>달걀</li>
</ul>
</section>
</section>
<footer>바닥글</footer>받은 HTML의 <body>에는 단추만 있고 목록이 없습니다. 그런데 페이지 소스의 <script> 안에서 달걀을 찾으면 두 번 나옵니다. 서버가 그린 재료 목록이 Fold의 children으로 글이 되어 실린 자리입니다(①이 아님). 그래서 누르면 서버에 다시 묻지 않고 바로 펼쳐집니다. 누른 뒤 브라우저가 새로 보낸 요청은 없습니다(③이 아님).
이 판이 이 레슨의 끝 판입니다.
자주 틀리는 곳
틀린 생각: 클라이언트 컴포넌트 안에 놓은 것은 모두 클라이언트다.
Fold 안에서 펼쳐지니, 재료 목록도 브라우저에서 돌 것 같습니다.
맞는 규칙: children으로 끼운 서버 컴포넌트는 서버에서 그린 결과로 건너가고, 서버 컴포넌트 그대로입니다. 2절에서 재료 목록을 부름은 서버 터미널과 [Prerender] 줄에만 있었습니다.
틀린 생각: 'use client' 줄이 있는 파일만 클라이언트다.
Ingredients.tsx에는 줄이 없으니, 누가 import 해도 서버일 것 같습니다.
맞는 규칙: 클라이언트 파일이 import 한 것은 줄이 없어도 클라이언트로 끌려갑니다(해 보기). 서버에서만 돌아야 하는 파일은 맨 위에 import 'server-only';를 두면, 클라이언트 쪽이 끌어올 때 빌드가 cannot be imported from과 a Client Component module이 든 오류로 멈춥니다(단원 8 환경 변수에서 다시 봅니다).
틀린 생각: 객체를 넘기면 클라이언트 컴포넌트가 쓰는 값만 브라우저로 간다.
별 단추는 recipe.favorite만 읽으니, 그 값만 갈 것 같습니다.
맞는 규칙: 넘긴 객체는 통째로 글이 되어 쪽에 실립니다. 1절에서 페이지 소스에 재료 밀가루까지 있었습니다. 레시피는 감출 값이 없어 통째로 넘겼지만, 브라우저에 보이면 안 되는 값이 든 객체는 필요한 값만 골라 넘깁니다.
확인 문제
문제 1. 서버 컴포넌트인 쪽이 클라이언트 컴포넌트 Card에 props를 넘깁니다. byTime은 쪽 파일에 둔 함수입니다. 쪽이 500으로 멈추는 것은 무엇일까요?
- ①
title="김치볶음밥" - ②
tags={['한식', '밥']} - ③
sort={byTime}
정답
③입니다. 함수는 글로 바꿀 수 없어, 해 보기의 format처럼 쪽이 멈춥니다.
- ① 글은 그대로 글로 실립니다.
- ② 글 배열도 글로 바꿀 수 있습니다. 1절의 재료 배열도 건너갔습니다.
문제 2. 'use client'가 있는 Tabs.tsx가, 'use client'가 없는 Panel.tsx를 import 해 그립니다. Panel은 어느 쪽 컴포넌트일까요?
- ① 서버 컴포넌트
- ② 클라이언트 컴포넌트
- ③ 빌드가 멈춰 어느 쪽도 아니다
정답
②입니다. 클라이언트 파일이 import 한 것은 줄이 없어도 클라이언트로 끌려갑니다(해 보기의 Ingredients).
- ① 줄이 없는 파일은 누가 import 하느냐에 따라 갈립니다. 서버 쪽 파일이 import 하면 서버, 클라이언트 파일이 import 하면 클라이언트입니다.
- ③ 오류가 아닙니다. 빌드가 멈추는 것은
import 'server-only'를 둔 파일을 끌어올 때입니다.
문제 3. 1절에서 별 단추에 recipe={r}를 넘긴 뒤, 목록 쪽 페이지 소스의 <script> 안에 밀가루가 생겼습니다. 까닭은 무엇일까요?
- ① 넘긴 레시피 객체가 글로 바뀌어 쪽과 함께 실려서
- ② 브라우저가
lib/recipes.ts를 받아 다시 읽어서 - ③ 서버가
<body>의 별 단추 안에 재료를 그려서
정답
①입니다. 브라우저도 하이드레이션 때 별 단추를 다시 부르므로, 넘긴 props를 글로 바꿔 함께 보냅니다.
- ② 별 단추가
lib/recipes.ts에서 가져온 것은 타입Recipe뿐이라, 그 파일은 JS로 가지 않습니다.밀가루는 JS 파일이 아니라 페이지 소스의<script>안에 있습니다. - ③
<body>에는밀가루가 없고,<script>안에만 있습니다.
단원 3을 마쳤습니다. 리액트 판의 세 한계 가운데 '주소가 하나'와 '받은 HTML이 빔', 둘을 풀었습니다. 남은 '그 브라우저에만 저장'은 단원 6에서 서버 함수로 풉니다.
이 레슨에서 바꾼 파일
components/FavoriteButton.tsx — recipe를 받아 별의 처음 값을 recipe.favorite으로
'use client';
import {
useState,
} from 'react';
import type {
Recipe,
} from '@/lib/recipes';
function FavoriteButton({
recipe,
}: {
recipe: Recipe;
}) {
const [starred, setStarred] =
useState(recipe.favorite);
function handleClick() {
setStarred(!starred);
}
return (
<button
onClick={handleClick}
>
{starred ? '★' : '☆'}
</button>
);
}
export default FavoriteButton;app/recipes/page.tsx — 별 단추에 recipe={r}를 넘김
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
recipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
export default function Page() {
return (
<ul>{recipes.map(item)}</ul>
);
}components/Fold.tsx — 새로 만듦. children을 접었다 펴는 단추
'use client';
import {
useState,
type ReactNode,
} from 'react';
function Fold({
children,
}: {
children: ReactNode;
}) {
const [open, setOpen] =
useState(false);
const label = open
? '재료 접기'
: '재료 보기';
function handleClick() {
setOpen(!open);
}
return (
<section>
<button
onClick={handleClick}
>
{label}
</button>
{open && children}
</section>
);
}
export default Fold;app/recipes/[id]/page.tsx — 재료 목록 Ingredients를 Fold의 children으로 끼움
import {
notFound,
} from 'next/navigation';
import {
recipes,
} from '@/lib/recipes';
import Fold from
'@/components/Fold';
export const
generateStaticParams = () =>
recipes.map((r) => ({
id: r.id,
}));
function Ingredients({
items,
}: {
items: string[];
}) {
return (
<ul>
{items.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
);
}
async function Page({
params,
}: PageProps<'/recipes/[id]'>) {
const { id } = await params;
const found = recipes.find(
(r) => r.id === id,
);
if (!found) {
notFound();
}
const items =
found.ingredients;
return (
<>
<h2>{found.title}</h2>
<Fold>
<Ingredients
items={items}
/>
</Fold>
</>
);
}
export default Page;이 단원 끝 파일
app/layout.tsx
import './globals.css';
import TabBar from
'@/components/TabBar';
function RootLayout({
children,
}: LayoutProps<'/'>) {
return (
<html lang="ko">
<body>
<TabBar />
{children}
<footer>바닥글</footer>
</body>
</html>
);
}
export default RootLayout;components/TabBar.tsx
'use client';
import Link from 'next/link';
import {
usePathname,
} from 'next/navigation';
function TabBar() {
const path = usePathname();
const mark = (href: string) =>
path.includes(href)
? '▸ '
: '';
return (
<nav>
<Link href="/recipes">
{mark('/recipes')}목록
</Link>
·<Link href="/stats">
{mark('/stats')}통계
</Link>
</nav>
);
}
export default TabBar;app/recipes/page.tsx
import Link from 'next/link';
import FavoriteButton from
'@/components/FavoriteButton';
import {
recipes,
type Recipe,
} from '@/lib/recipes';
const item = (r: Recipe) => (
<li key={r.id}>
<Link
href={`/recipes/${r.id}`}
>
{r.title}
</Link>
<FavoriteButton
recipe={r}
/>
</li>
);
export default function Page() {
return (
<ul>{recipes.map(item)}</ul>
);
}components/FavoriteButton.tsx
'use client';
import {
useState,
} from 'react';
import type {
Recipe,
} from '@/lib/recipes';
function FavoriteButton({
recipe,
}: {
recipe: Recipe;
}) {
const [starred, setStarred] =
useState(recipe.favorite);
function handleClick() {
setStarred(!starred);
}
return (
<button
onClick={handleClick}
>
{starred ? '★' : '☆'}
</button>
);
}
export default FavoriteButton;app/recipes/[id]/page.tsx
import {
notFound,
} from 'next/navigation';
import {
recipes,
} from '@/lib/recipes';
import Fold from
'@/components/Fold';
export const
generateStaticParams = () =>
recipes.map((r) => ({
id: r.id,
}));
function Ingredients({
items,
}: {
items: string[];
}) {
return (
<ul>
{items.map((i) => (
<li key={i}>{i}</li>
))}
</ul>
);
}
async function Page({
params,
}: PageProps<'/recipes/[id]'>) {
const { id } = await params;
const found = recipes.find(
(r) => r.id === id,
);
if (!found) {
notFound();
}
const items =
found.ingredients;
return (
<>
<h2>{found.title}</h2>
<Fold>
<Ingredients
items={items}
/>
</Fold>
</>
);
}
export default Page;components/Fold.tsx
'use client';
import {
useState,
type ReactNode,
} from 'react';
function Fold({
children,
}: {
children: ReactNode;
}) {
const [open, setOpen] =
useState(false);
const label = open
? '재료 접기'
: '재료 보기';
function handleClick() {
setOpen(!open);
}
return (
<section>
<button
onClick={handleClick}
>
{label}
</button>
{open && children}
</section>
);
}
export default Fold;