Step 6: Add to Cart
Part of the Next.js Essentials section of Coddy's React journey — lesson 44 of 47.
Challenge
EasyAdd a cart button, and keep the page on the server.
- Create
components/CartButton.jsxstarting with'use client';. - Hold a
countinuseState(0). Render a<button id="add-to-cart" className="primary">readingAdd to cartthat increments it on click. - Below it render
<p id="cart-count" className="cart">reading the count, thenx, then thenameprop, thenin the cart, for example2 x Street Tacos in the cart. - In
app/menu/[slug]/page.jsx, render<CartButton name={dish.name} />under the price. Do not add'use client'to the page.
Try it yourself
import Link from 'next/link';
import './globals.css';
export const metadata = {
title: {
default: 'Coddy Eats',
template: '%s | Coddy Eats',
},
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<nav className="nav">
<Link className="brand" href="/">Coddy Eats</Link>
<Link id="nav-menu" href="/">Menu</Link>
<Link id="nav-desserts" href="/?category=dessert">Desserts</Link>
</nav>
<div className="container">
{children}
</div>
</body>
</html>
);
}