# Built-in Components

Course: [Blazor](https://www.devtutorials.ai/learn/blazor) · Section: Blazor Components
Source: https://www.devtutorials.ai/learn/blazor/components/built-in-components

> Blazor's ready-made components: Router and @page routes, query strings and route patterns, the Not Found page, NavLink, FocusOnNavigate, PageTitle, HeadContent, Virtualize with ItemsProvider and ErrorBoundary.

## Built-in Components Overview

- Built-in components are ready-made Blazor components provided by the framework.
- They help build common UI features without creating components from scratch.
- You use them like your own components, for example `<NavLink>` or `<Virtualize>`.
- Using built-in components reduces time and keeps applications consistent.

**Real-World Example:**

- Ravi needs menu links that show the open page.
- He needs a title in the browser tab.
- He needs a long list of past orders.
- Blazor's built-in components already do all of this.

The Router and page titles would change **this** website, so this lesson shows them with pictures and code to read. The other components run live in the code boxes.

**Simple lesson:** Built-in components do common jobs for you. Use them like any other component.

## Router (Routes.razor)

- The **Router** looks at the web address and shows the page that matches it.
- It lives in `Components/Routes.razor`, which you met in **Project Structure and Running the App**.
- `RouteView` shows the page inside a **layout** (the frame with the menu). `DefaultLayout` picks that layout.
- `NotFoundPage` is the page to show when no page matches.

`}
/>

### Pages and Routing (@page)

- A component with `@page "/menu"` becomes a **page** at that address.
- When you visit `/menu`, the Router finds that component and shows it.
- One component can have more than one `@page` line.
- A part in braces is a **route parameter**: `@page "/tea/{Name}"`. Visiting `/tea/masala` sets the page's `[Parameter] Name` to `"masala"`.

Watch the animation. The Router reads the address and picks the matching page.

<figure className="blz-fig">
<svg viewBox="0 0 640 210" role="img" aria-labelledby="fig-bi-router">
  <title id="fig-bi-router">Animation: the address bar shows /menu, then /order. The Router compares the address with each page's @page line and highlights the matching page: Menu.razor for /menu, Order.razor for /order.</title>
  <rect className="box" x="10" y="80" width="170" height="40" rx="20" />
  <text className="t m" x="95" y="105" textAnchor="middle" style={{ fontSize: 13 }}>
    <tspan>/menu<animate attributeName="opacity" values="1;1;0;0" keyTimes="0;0.49;0.5;1" dur="4s" repeatCount="indefinite" /></tspan>
  </text>
  <text className="t m" x="95" y="105" textAnchor="middle" style={{ fontSize: 13 }} opacity="0">/order<animate attributeName="opacity" values="0;0;1;1" keyTimes="0;0.49;0.5;1" dur="4s" repeatCount="indefinite" /></text>
  <rect className="org" x="230" y="76" width="130" height="48" rx="10" />
  <text className="t" x="295" y="105" textAnchor="middle" style={{ fontSize: 14, fontWeight: 700 }}>Router</text>
  <path className="line" d="M180 100 H226" />
  <rect className="box" x="420" y="20" width="210" height="44" rx="8">
    <animate attributeName="stroke-width" values="4;4;1;1" keyTimes="0;0.49;0.5;1" dur="4s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="525" y="47" textAnchor="middle" style={{ fontSize: 12 }}>Menu.razor  @page "/menu"</text>
  <rect className="box" x="420" y="80" width="210" height="44" rx="8" style={{ strokeWidth: 1 }}>
    <animate attributeName="stroke-width" values="1;1;4;4" keyTimes="0;0.49;0.5;1" dur="4s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="525" y="107" textAnchor="middle" style={{ fontSize: 12 }}>Order.razor  @page "/order"</text>
  <rect className="box" x="420" y="140" width="210" height="44" rx="8" />
  <text className="t m" x="525" y="167" textAnchor="middle" style={{ fontSize: 12 }}>Home.razor  @page "/"</text>
  <path className="line" d="M360 100 L416 42" /><path className="line" d="M360 100 H416" /><path className="line" d="M360 100 L416 162" />
</svg>
<figcaption>The Router matches the address with each page's @page line.</figcaption>
</figure>

### Query Strings

- A **query string** is the part of a web address after `?`, like `/order?cups=2&tea=masala`.
- It holds extra values as `name=value` pairs, joined with `&`.
- Use it for optional values, like a search word, a filter or a page number.
- In a page, add `[SupplyParameterFromQuery]` to a property, like `public int Cups { get; set; }`. Blazor fills it from the query string: `cups=2` sets `Cups` to `2`.

The code box cannot change this website's address, so in the below example the address is a variable. The page reads `cups` and `tea` from it, the same way `[SupplyParameterFromQuery]` does for you.

<p>Cups: @cups</p>
<p>Tea: @tea</p>

@code {
      // Change the values after ? and press Run.
      private string address = "/order?cups=2&tea=masala";

      private string cups = "";
      private string tea = "";

      protected override void OnInitialized()
      {
          var query = new Uri("https://localhost" + address).Query;
          var values = System.Web.HttpUtility.ParseQueryString(query);

          cups = values["cups"] ?? "not given";
          tea = values["tea"] ?? "not given";
      }
}
`,
  }}
/>

**What you see:** "Cups: 2" and "Tea: masala". Try it: change the address to `/order?cups=5` and press **▶ Run**. Tea shows "not given", because the address has no `tea` value.

### Route Patterns (Multiple, Optional, Constraints, Catch-All)

| Pattern | Example | Matches |
|---|---|---|
| **Multiple** routes | two lines: `@page "/menu"` and `@page "/drinks"` | `/menu` and `/drinks` show the same page |
| **Optional** parameter | `@page "/order/{Cups:int?}"` | `/order` and `/order/3` |
| **Constraint** | `@page "/order/{Id:int}"` | `/order/5`, but not `/order/abc` |
| **Catch-all** | `@page "/files/{*Path}"` | `/files/a/b/c`, Path = `"a/b/c"` |

- A **constraint** like `:int` checks the type. If the address does not fit, the page does not match.
- The parameter type must match the constraint: `{Id:int}` needs `public int Id`.

Common constraints: `:int`, `:bool`, `:guid`, `:datetime` and `:decimal`. Add `?` to make a parameter optional: `{Id:int?}` needs `public int? Id`.

### Not Found Page

- If no page matches, Blazor shows a **Not Found** page.
- The .NET 10 template has `Components/Pages/NotFound.razor` with `@page "/not-found"`.
- `Routes.razor` points to it with `NotFoundPage="typeof(Pages.NotFound)"`.

**Simple lesson:** The Router picks a page by its `@page` pattern. Braces make parts of the address into parameters.

## NavLink

- `NavLink` is a link, like `<a>`, with one extra job: it knows when its page is open.
- When the address matches its `href`, it adds the CSS class `active`.
- The template's side menu (`NavMenu.razor`) uses `NavLink` for Home, Counter and Weather.

### Active Link Styling

- Style the `active` class to highlight the open page, for example bold text or a coloured background.
- `Match="NavLinkMatch.All"` means "active only when the **whole** address matches". Use it for the home link `""`. Otherwise `/` would match every page.
- Without it (the default, `Prefix`), `/menu` is also active on `/menu/specials`.

In the below example, the links point to real pages of this website. `NavLink` compares each `href` with the address of the page you are reading now, and adds `active` to the links that match. The `<style>` block colours active links purple.

      .demo-menu a {
          display: block;
          padding: 6px 10px;
          margin: 4px 0;
          border: 1px solid #ddd;
          border-radius: 6px;
          color: #3a0647;
          text-decoration: none;
      }

      .demo-menu a.active {
          background: #6d28d9;
          color: white;
          font-weight: bold;
      }
</style>

<p>You are on: <b>@thisPage</b></p>

@* @onclick:preventDefault keeps you on this lesson when you click a link *@
<nav class="demo-menu" @onclick:preventDefault>
      <div @onclick='() => Clicked("/")'>
          <NavLink href="/" Match="NavLinkMatch.All">Home (whole address)</NavLink>
      </div>
      <div @onclick='() => Clicked("/learn/blazor")'>
          <NavLink href="/learn/blazor">Blazor course (start of address)</NavLink>
      </div>
      <div @onclick='() => Clicked("/learn/blazor")'>
          <NavLink href="/learn/blazor" Match="NavLinkMatch.All">Blazor course (whole address)</NavLink>
      </div>
      <div @onclick="() => Clicked(thisPage)">
          <NavLink href="@thisPage">This lesson</NavLink>
      </div>
      <div @onclick='() => Clicked("/learn/blazor/components/component-lifecycle")'>
          <NavLink href="/learn/blazor/components/component-lifecycle">Next lesson</NavLink>
      </div>
</nav>

<p>@message</p>

@code {
      private string thisPage = "";
      private string message = "Click a link.";

      private void Clicked(string address)
      {
          message = $"In a real app, this opens {address}, and the highlight moves to its link.";
      }

      protected override void OnInitialized()
      {
          // The address of this page, without the website name, like /learn/blazor/...
          thisPage = new Uri(Nav.Uri).AbsolutePath;
      }
}
`,
  }}
/>

**What you see:** two purple links. **This lesson** matches the whole address. **Blazor course (start of address)** is also active, because the address starts with `/learn/blazor`. The same link with `Match="NavLinkMatch.All"` is not active, and neither are **Home** and **Next lesson**. Click a link: the box stays on this lesson and tells you which page a real app would open.

<figure className="blz-fig">
<svg viewBox="0 0 560 160" role="img" aria-labelledby="fig-bi-navlink">
  <title id="fig-bi-navlink">Animation: three menu links, Home, Menu and Order. As the page changes, the active highlight moves from Home to Menu to Order.</title>
  <rect x="20" y="20" width="160" height="120" rx="10" style={{ fill: "#3a0647" }} />
  <rect x="28" y="30" width="144" height="30" rx="6" style={{ fill: "rgba(255,255,255,0.3)" }}>
    <animate attributeName="y" values="30;66;102" dur="4.5s" repeatCount="indefinite" calcMode="discrete" />
  </rect>
  <text x="44" y="50" style={{ fill: "#fff", fontFamily: "var(--sans)", fontSize: 13 }}>Home</text>
  <text x="44" y="86" style={{ fill: "#fff", fontFamily: "var(--sans)", fontSize: 13 }}>Menu</text>
  <text x="44" y="122" style={{ fill: "#fff", fontFamily: "var(--sans)", fontSize: 13 }}>Order</text>
  <rect className="box" x="220" y="20" width="320" height="40" rx="20" />
  <text className="t m" x="240" y="45" style={{ fontSize: 13 }}>
    <tspan>https://localhost/<animate attributeName="opacity" values="1;0;0" dur="4.5s" repeatCount="indefinite" calcMode="discrete" /></tspan>
  </text>
  <text className="t m" x="240" y="45" style={{ fontSize: 13 }} opacity="0">https://localhost/menu<animate attributeName="opacity" values="0;1;0" dur="4.5s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t m" x="240" y="45" style={{ fontSize: 13 }} opacity="0">https://localhost/order<animate attributeName="opacity" values="0;0;1" dur="4.5s" repeatCount="indefinite" calcMode="discrete" /></text>
  <text className="t" x="240" y="100" style={{ fontSize: 13 }}>The link for the open page</text>
  <text className="t" x="240" y="120" style={{ fontSize: 13 }}>gets class="active".</text>
</svg>
<figcaption>NavLink adds the active class to the link for the open page.</figcaption>
</figure>

**Simple lesson:** Use `NavLink` for menu links. Style its `active` class to show where the user is.

## FocusOnNavigate

- After a page change, a keyboard or screen-reader user should start at the new page's heading.
- `FocusOnNavigate` moves focus to the element you choose with `Selector`, such as `"h1"`.
- The template already has it in `Routes.razor` (see the code under **Router (Routes.razor)** above).

**Simple lesson:** `FocusOnNavigate` helps keyboard and screen-reader users after each page change.

## PageTitle

- `<PageTitle>` sets the text in the browser tab.
- Put it in any page. When that page opens, the tab shows its title.
- It works because `App.razor` has `<HeadOutlet />`, which writes it into the page's `head`.

## HeadContent

- `<HeadContent>` adds other tags to the `head`, such as a description for search engines.

      <meta name="description" content="Fresh masala, ginger and lemon tea." />

<h1>Menu</h1>
`}
/>

**Simple lesson:** `PageTitle` sets the tab title. `HeadContent` adds tags to the `head`.

## Virtualize

### Virtualization Basics

- A list with 10,000 rows is slow if Blazor makes HTML for all of them.
- `<Virtualize>` makes HTML **only for the rows you can see**, plus a few extra.
- As you scroll, it swaps rows in and out. The list feels complete, but the page stays fast.
- The list must be inside a box with a fixed height and scrolling.

<figure className="blz-fig">
<svg viewBox="0 0 560 220" role="img" aria-labelledby="fig-bi-virt">
  <title id="fig-bi-virt">Animation: a long list of 10,000 orders. A window slides down the list. Only the rows inside the window are drawn as HTML; the rest are empty space.</title>
  <rect className="box" x="20" y="10" width="200" height="200" rx="8" style={{ strokeDasharray: "4 4" }} />
  <text className="t" x="120" y="110" textAnchor="middle" style={{ fontSize: 12 }}>10,000 orders</text>
  <text className="t" x="120" y="128" textAnchor="middle" style={{ fontSize: 11 }}>(not drawn)</text>
  <g>
    <animateTransform attributeName="transform" type="translate" values="0,0; 0,130; 0,0" dur="5s" repeatCount="indefinite" />
    <rect className="grn" x="14" y="14" width="212" height="62" rx="6" style={{ strokeWidth: 2 }} />
    <text className="t m" x="30" y="34" style={{ fontSize: 11 }}>Order #… drawn</text>
    <text className="t m" x="30" y="50" style={{ fontSize: 11 }}>Order #… drawn</text>
    <text className="t m" x="30" y="66" style={{ fontSize: 11 }}>Order #… drawn</text>
  </g>
  <text className="t" x="260" y="60" style={{ fontSize: 13, fontWeight: 700 }}>Green box = what you can see</text>
  <text className="t" x="260" y="84" style={{ fontSize: 13 }}>Only these rows become HTML.</text>
  <text className="t" x="260" y="108" style={{ fontSize: 13 }}>Scroll, and the rows change.</text>
</svg>
<figcaption>Virtualize draws only the rows in view.</figcaption>
</figure>

In the below example, `<Virtualize>` shows 10,000 orders. The HTML inside it is one row, and `order` is the current item. The list sits in a scrolling box with a fixed height, which Virtualize needs.

<div style="height: 220px; overflow-y: auto; border: 1px solid #ccc;">
          <div style="height: 30px; padding: 4px;">
              Order #@order.Id: @order.Tea
          </div>
</div>

@code {
      private record Order(int Id, string Tea);

      private List<Order> orders = Enumerable.Range(1, 10000)
          .Select(i => new Order(i, i % 2 == 0 ? "Masala Tea" : "Ginger Tea"))
          .ToList();
}
`,
  }}
/>

**What you see:** a box you can scroll through all 10,000 orders. It scrolls smoothly, because only about 20 rows exist at a time.

### On-Demand Loading (ItemsProvider)

- With `Items`, the whole list must already be in memory. Ravi's 5,000 past orders live in a database, so loading them all at once is slow.
- With `ItemsProvider`, Virtualize **asks for rows only when it needs them**, like "give me rows 40 to 60".
- `Placeholder` is what each row shows while it loads.

In the below example, Virtualize calls `LoadOrders` with the rows it needs (`StartIndex` and `Count`). The method waits a moment, like a database, and returns those rows and the total, 5,000. Rows show "Loading…" until they arrive.

              <div style="height: 30px; padding: 4px;">@order</div>
              <div style="height: 30px; padding: 4px; color: gray;">Loading…</div>
</div>

@code {
      private async ValueTask<ItemsProviderResult<string>> LoadOrders(ItemsProviderRequest request)
      {
          await Task.Delay(300); // pretend to call a database
          Console.WriteLine($"Loading rows {request.StartIndex} to {request.StartIndex + request.Count}");

          var rows = Enumerable.Range(request.StartIndex, request.Count)
              .Select(i => $"Past order #{i + 1}");
          return new ItemsProviderResult<string>(rows, 5000);
      }
}
`,
  }}
/>

**What you see:** scroll fast, and rows show **Loading…** for a moment. The **Console** shows which rows were asked for, like "Loading rows 40 to 60".

**Simple lesson:** `Virtualize` draws only the visible rows. Use `ItemsProvider` to load rows as they are needed.

## ErrorBoundary

### Error Handling and Recovery

- Normally, if one component has an error, the whole page stops working.
- `<ErrorBoundary>` puts a safety wall around part of the page. If a component **inside** it fails, only that part shows an error message. Everything outside keeps working.
- Put the normal content in `<ChildContent>` and the error message in `<ErrorContent>`.
- `Recover()` takes the wall down and shows the normal content again, so the user can try again.

In the below example, `OrderBox.razor` throws an error on the fourth click. `Home.razor` wraps it in `ErrorBoundary`, so only the box shows the error message. **Try again** calls `Recover()`.

<p>This part keeps working, even if the order box fails.</p>

          <p style="color: red;">Sorry, the order box had a problem.</p>
          <button @onclick="TryAgain">Try again</button>

@code {
      private ErrorBoundary? boundary;

      private void TryAgain()
      {
          boundary?.Recover();
      }
}
`,
    "Components/OrderBox.razor": `<p>Cups: @cups</p>
<button @onclick="AddCup">Add cup</button>

@code {
      private int cups = 0;

      private void AddCup()
      {
          cups++;
          if (cups > 3)
          {
              throw new InvalidOperationException("Too many cups!");
          }
      }
}
`,
  }}
/>

**What you see:** click **Add cup** four times. The order box is replaced by "Sorry, the order box had a problem", but the heading still shows. Click **Try again** to get a fresh order box.

`ErrorBoundary` is a safety net, not a fix. Still find and fix the real error. The **Console** shows its details.

**Simple lesson:** Wrap risky parts in `ErrorBoundary`, so one error does not break the whole page.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Using `<a>` for menu links | A plain link highlights itself | Use `NavLink` and style `.active` | The open page is never highlighted |
| Home link without `Match="NavLinkMatch.All"` | `/` only matches the home page | Add `Match="NavLinkMatch.All"` | Home looks active on every page |
| Two pages with the same `@page` address | Blazor picks one | Give every page its own address | An error about ambiguous routes |
| Virtualize without a fixed height | It knows the screen size | Put it in a box with a height and `overflow-y: auto` | All rows render, or none scroll |
| Expecting `ErrorBoundary` to fix the error | It makes the error go away | It only shows a message. Fix the real bug | The same error comes back |
| Reading a query value without a default | The value is always there | Use `?? "not given"` | `null` where you expected text |

</div>

## Check Yourself

## Exercises

## What to Remember

- `Router` (in `Routes.razor`) shows the page whose `@page` pattern matches the address. `{Name}` makes a route parameter.
- `NavLink` adds `active` to the link for the open page. `FocusOnNavigate` moves focus after a page change.
- `PageTitle` sets the tab title. `HeadContent` adds `head` tags.
- `Virtualize` draws only visible rows. `ItemsProvider` loads rows on demand.
- `ErrorBoundary` keeps one error from breaking the whole page. `Recover()` resets it.

Next: **Component Lifecycle**
