Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 72 Β· Practice and Interviews

UI Recipes: Carousel, Video, YouTube Embed, Modal, Date Picker, Spinner

Build common UI widgets in the Next.js App Router: an accessible carousel, modal, date picker and spinner, plus video and YouTube embeds and lazy loading with next/dynamic.

Most real pages need the same handful of widgets: an image carousel, a modal dialog, a video player, a YouTube embed, a date picker and a loading spinner. You could install a library for each. Often you do not need to, and a small component of your own is lighter, easier to style and easier to make accessible. In the App Router there is an extra question for each widget: is it a Server Component or a Client Component, and how do I keep its JavaScript off the pages that do not use it?

This lesson gives you a short recipe for each widget. The React parts run live in the editors below (they are plain React, which is the same code that goes into a "use client" file in a Next.js project). The Next.js-specific parts, such as directives and next/dynamic, are read-only blocks, because Next.js cannot run on this site.

Widgets in this lesson

Carousel Buttons, a live region and keyboard use.
Modal The native dialog element.
Date picker A native input, formatted with Intl.
Spinner CSS only, announced to screen readers.

Plus video and YouTube embeds.

1 / 2

A rule that applies to every widget

Anything with state (useState), effects or event handlers such as onClick must be a Client Component, which means the file starts with "use client" (see Client Components and "use client"). The page that uses the widget can stay a Server Component. Put the directive on the smallest file that needs it, so the rest of the page does not ship JavaScript. For example, a product page stays on the server and imports a Gallery client component only for the interactive part.

TSX
// components/gallery.tsx (read-only)
"use client";

import { useState } from "react";

export function Gallery({ images }: { images: { src: string; alt: string }[] }) {
  const [index, setIndex] = useState(0);
  // ...same code as the carousel recipe below
  return <img src={images[index].src} alt={images[index].alt} />;
}

The recipes below show only the React part, the same way you would put it in such a file. Use the next/image component in place of plain <img> in a real project, so pictures are resized and lazy loaded.

A carousel shows one slide at a time with previous and next controls. The accessible version needs three things: real <button> elements (so the keyboard works), labels that say what the buttons do, and a live region, an element that screen readers announce when its text changes, so a user who cannot see the picture is told which slide appeared. Do not auto-advance slides by default: moving content is hard to read and a problem for some users.

An accessible carousel

Press Tab to reach each button and Enter or Space to use it. The % arithmetic in go wraps from the last slide to the first. For swiping, large galleries and many features, a dedicated library such as Embla or Swiper is worth it; wrap it in your own client component so the rest of the app does not depend on it.

Recipe 2: a modal dialog

A modal blocks the page until it is closed. Getting focus handling right (the focus must move into the modal, stay inside it and return to the button afterwards, and Escape must close it) used to take a lot of code. The native HTML <dialog> element does all of that when opened with showModal(). In React you reach it through a ref.

A modal with the native dialog element

The browser provides the focus trap, the Escape key, the dimmed backdrop (style it with dialog::backdrop) and the "inert" background. In Next.js, a modal that has its own URL (so a refresh keeps it open and the back button closes it) is a different technique called an intercepting route, covered in Parallel and Intercepting Routes.

Recipe 3: a date picker

For most forms the native <input type="date"> is the best date picker: it is accessible, localized by the browser, works on phones and costs no JavaScript. The value is always a plain YYYY-MM-DD string, whatever the display language is. Use min and max to limit the choices and format the result for people with Intl.DateTimeFormat.

A native date picker with limits

Reach for a library such as React Day Picker only when you need a range picker, a calendar that always shows on the page, or exact control over the look. As with every library, import it from a client component.

Recipe 4: a spinner and the loading states Next.js gives you

A spinner can be pure CSS. Give it role="status" and a visually hidden text so screen readers announce it. Respect users who asked their system for less motion.

A CSS spinner with accessible text

In Next.js you often need no hand-written spinner. A loading.tsx file shows a fallback while a route loads, and <Suspense fallback={<Spinner />}> covers one slow part of a page (see Loading, Error and Not Found and Streaming and Suspense). For a form button, useFormStatus or useActionState tells you when a Server Action is pending (Forms and Actions).

Recipe 5: video

For a file that you host yourself, the plain <video> element is enough, and it is a Server Component-friendly tag, because it needs no JavaScript:

TSX
// read-only
<video controls preload="metadata" poster="/videos/intro-poster.jpg" width={640}>
  <source src="/videos/intro.webm" type="video/webm" />
  <source src="/videos/intro.mp4" type="video/mp4" />
  <track kind="captions" src="/videos/intro.en.vtt" srcLang="en" label="English" default />
  Your browser does not support video.
</video>

Notes: put the files in public/ or, for large files, on a storage service or video platform with a CDN, because your Next.js server is not a good video server. preload="metadata" loads only the duration and first frame, which saves bandwidth. Always add captions with <track>. If a video must start playing on its own, add muted, playsInline and autoPlay together (browsers block sound autoplay), and avoid it for anything long. The controls attribute gives you an accessible player for free. If you want custom buttons you need a Client Component with a ref and video.play() calls.

Recipe 6: a YouTube embed that does not slow the page

A standard YouTube <iframe> downloads hundreds of kilobytes of third-party code, even if nobody presses play. The fix is a facade: show a thumbnail and a button, and create the iframe only after a click. The privacy-friendlier domain youtube-nocookie.com avoids tracking cookies until the user plays the video.

TSX
// components/youtube-facade.tsx (read-only)
"use client";

import { useState } from "react";

export function YouTubeFacade({ id, title }: { id: string; title: string }) {
  const [active, setActive] = useState(false);

  if (active) {
    return (
      <iframe
        width="560"
        height="315"
        src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1`}
        title={title}
        allow="autoplay; encrypted-media; picture-in-picture"
        allowFullScreen
      />
    );
  }

  return (
    <button type="button" onClick={() => setActive(true)} aria-label={`Play video: ${title}`}>
      <img src={`https://i.ytimg.com/vi/${id}/hqdefault.jpg`} alt="" width={480} height={360} />
      <span aria-hidden="true">β–Ά</span>
    </button>
  );
}

The official @next/third-parties package ships a ready-made <YouTubeEmbed videoid="..." /> that does the same lazy loading, and is covered in Analytics and Third-Party Libraries. Add a title to every iframe so screen reader users know what it holds. If you set a Content Security Policy, allow the video domain in frame-src.

Loading heavy widgets late with next/dynamic

A rich date picker, a chart or an editor can add tens of kilobytes. If it only appears after a click or lower on the page, load it on demand with next/dynamic. The code for the widget then goes into its own chunk that the browser downloads when needed. This is the same lazy loading that React.lazy offers, with extra options.

TSX
// app/events/new/page.tsx (read-only)
import dynamic from "next/dynamic";

const RichDatePicker = dynamic(() => import("@/components/rich-date-picker"), {
  loading: () => <p>Loading calendar…</p>,
  ssr: false,
});

ssr: false means "do not render this on the server at all", which is right for widgets that touch window at import time. Note that ssr: false is only allowed inside a Client Component (a file with "use client"), so create a small client wrapper when you need it from a Server Component. See Bundle Size and Performance for how to measure whether lazy loading helped.

Check your understanding

Quick check Β· 4 questions

of 4 answered You scored / 4 Β· perfect!

  1. 1. Where should the 'use client' directive go for a carousel on a product page?

    State and click handlers require a Client Component, but the directive only needs to be on the smallest file that uses them.
  2. 2. Why is the native <dialog> element a good basis for a modal?

    The browser handles the hard accessibility parts, so your code only has to open and close it.
  3. 3. What does a YouTube 'facade' do?

    The iframe pulls in a lot of third-party code. Deferring it until the click keeps the page fast.
  4. 4. Where is next/dynamic with ssr: false allowed?

    Turning off server rendering only makes sense for client code, so Next.js requires the call to live in a Client Component.

Summary

  • Interactive widgets are Client Components. Put "use client" on the smallest file and keep the page itself on the server.
  • A carousel needs real buttons, labels and a live region; do not auto-advance by default.
  • The native <dialog> with showModal() and the native <input type="date"> give you accessibility without libraries.
  • A spinner is CSS plus role="status" and hidden text. Next.js also has loading.tsx, Suspense and useFormStatus for loading states.
  • Host video as <video> with captions, and load YouTube through a facade or @next/third-parties.
  • Use next/dynamic to load heavy widgets only when they are needed.

Next: Cheat Sheet