# Components Basics

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

> What a Blazor component is and how it renders, creating and using components, parent and child components, [Parameter], [EditorRequired], cascading values, ChildContent, EventCallback and CSS isolation.

## Components Overview

- A **component** is one piece of the screen, like a menu card, a button or a whole page.
- Each component is one `.razor` file. It has its own HTML and its own C#.
- You build a page by putting components together, like building blocks.
- You already made components in **Razor Syntax**. This chapter shows how they work together.

**Real-World Example:**

- Ravi's menu page shows ten teas.
- Each tea has a name, a price and an **Order** button.
- Ravi writes one `TeaCard` component and uses it ten times.
- When he changes the card's design, all ten cards change.

In the below example, `TeaCard.razor` draws one card. `Menu.razor` uses it three times with a different tea each time.

`,
    "Components/TeaCard.razor": `<div style="border: 1px solid #ccc; border-radius: 8px; padding: 8px; margin: 6px 0;">
      <b>@Name</b>: ₹@Price
</div>

@code {
      [Parameter] public string Name { get; set; } = "";
      [Parameter] public int Price { get; set; }
}
`,
  }}
/>

**What you see:** three cards that look the same, with different teas. Change the border colour once in `TeaCard.razor`, press **▶ Run**, and all three cards change.

**Simple lesson:** A component is a reusable piece of the screen in one `.razor` file.

## How Components Work

- Blazor turns each `.razor` file into a C# **class**. The file name becomes the class name: `TeaCard.razor` becomes `TeaCard`.
- When a component's data changes, Blazor **renders** it again: it works out the new HTML.
- Blazor then compares the new HTML with the old one. It changes **only** the parts that are different in the browser.
- This is why pages stay fast, even when they have many components.

Watch the animation. A click changes one number. Blazor updates only that one spot on the page.

<figure className="blz-fig">
<svg viewBox="0 0 640 220" role="img" aria-labelledby="fig-cb-render">
  <title id="fig-cb-render">Animation: a click on Add cup changes cups from 1 to 2. Blazor renders the component again, compares old and new, and updates only the number on the page. The heading and the button stay the same.</title>
  <defs><marker id="cb-a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 0 L10 5 L0 10 z" style={{ fill: "var(--muted)" }} /></marker></defs>
  <rect className="pur" x="10" y="60" width="140" height="70" rx="10" />
  <text className="t" x="80" y="88" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>1. Click</text>
  <text className="t m" x="80" y="110" textAnchor="middle" style={{ fontSize: 12 }}>cups++</text>
  <rect className="org" x="190" y="60" width="160" height="70" rx="10" />
  <text className="t" x="270" y="88" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>2. Render again</text>
  <text className="t" x="270" y="110" textAnchor="middle" style={{ fontSize: 12 }}>compare old and new</text>
  <path className="line" d="M150 95 H186" markerEnd="url(#cb-a1)" />
  <path className="line" d="M350 95 H396" markerEnd="url(#cb-a1)" />
  <rect className="box" x="400" y="20" width="230" height="180" rx="10" />
  <text className="t" x="515" y="44" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>3. Browser page</text>
  <rect className="blu" x="416" y="58" width="198" height="34" rx="6" />
  <text className="t" x="515" y="80" textAnchor="middle" style={{ fontSize: 12 }}>Order your tea (same)</text>
  <rect className="blu" x="416" y="100" width="198" height="34" rx="6">
    <animate attributeName="stroke-width" values="1;4;1" dur="2s" repeatCount="indefinite" />
  </rect>
  <text className="t" x="515" y="122" textAnchor="middle" style={{ fontSize: 12 }}>Cups: <tspan style={{ fontWeight: 700 }}>2</tspan> (updated)</text>
  <rect className="blu" x="416" y="142" width="198" height="34" rx="6" />
  <text className="t" x="515" y="164" textAnchor="middle" style={{ fontSize: 12 }}>Add cup button (same)</text>
  <circle r="6" cy="95" style={{ fill: "#7c3aed" }}><animate attributeName="cx" values="80;270;515" dur="2s" repeatCount="indefinite" /></circle>
</svg>
<figcaption>Blazor renders the component again, then changes only what is different.</figcaption>
</figure>

**Simple lesson:** A component is a class. When its data changes, Blazor updates only the changed parts of the page.

## Creating Components

### Component File (.razor)

A component file has up to three parts. Only the HTML is required.

      <b>@Name</b>
</div>

@* 3. C# (optional): data and methods *@
@code {
      [Parameter] public string Name { get; set; } = "";
}
`}
/>

### Naming and Folders

- The name **must start with a capital letter**: `TeaCard.razor`, not `teaCard.razor`. Blazor treats lowercase tags as HTML.
- Use clear names that say what it is: `TeaCard`, `OrderButton`, `ShopHeader`.
- **Pages** (with `@page`) go in `Components/Pages/`.
- **Reusable pieces** go in `Components/` or a folder you make, like `Components/Shop/`.
- If the folder is new, add its namespace to `_Imports.razor` (see **Project Structure and Running the App**). Then every page can use its components.

In Visual Studio: right-click a folder, then **Add** → **Razor Component**. In VS Code or the CLI: `dotnet new razorcomponent -n TeaCard -o Components`.

**Simple lesson:** One component per `.razor` file. Start the name with a capital letter.

## Using Components

- Use a component like an HTML tag, with its file name: `<TeaCard />`.
- A tag with nothing inside can close itself: `<TeaCard />`.
- You can use the same component as many times as you like.
- If you misspell the name, the editor shows a yellow line. Blazor cannot find a component with that name.

<p>Fresh tea, made to order.</p>
`,
    "Components/ShopHeader.razor": `<h3>☕ Ravi's Tea Shop</h3>
`,
  }}
/>

- Change `<ShopHeader />` to `<ShopHedder />` and wait a moment. A yellow line appears under the wrong name.

**Simple lesson:** Write `<ComponentName />` to use a component.

## Parent and Child Components

- When component A uses component B, A is the **parent** and B is the **child**.
- A page is usually a parent. The cards and buttons inside it are its children.
- Together they make a **component tree**.
- Data goes **down** the tree with parameters. Messages go **up** with events. You learn both below.

<figure className="blz-fig">
<svg viewBox="0 0 620 230" role="img" aria-labelledby="fig-cb-tree">
  <title id="fig-cb-tree">Animation: a component tree. Menu is the parent at the top. Two TeaCard children sit below it, and each card has an OrderButton child. Purple dots move down from parent to child for parameters. Orange dots move up from OrderButton to Menu for events.</title>
  <rect className="pur" x="240" y="16" width="140" height="40" rx="8" />
  <text className="t m" x="310" y="41" textAnchor="middle" style={{ fontSize: 13, fontWeight: 700 }}>Menu (parent)</text>
  <rect className="blu" x="90" y="96" width="140" height="40" rx="8" />
  <text className="t m" x="160" y="121" textAnchor="middle" style={{ fontSize: 13 }}>TeaCard</text>
  <rect className="blu" x="390" y="96" width="140" height="40" rx="8" />
  <text className="t m" x="460" y="121" textAnchor="middle" style={{ fontSize: 13 }}>TeaCard</text>
  <rect className="grn" x="90" y="176" width="140" height="40" rx="8" />
  <text className="t m" x="160" y="201" textAnchor="middle" style={{ fontSize: 12 }}>OrderButton</text>
  <rect className="grn" x="390" y="176" width="140" height="40" rx="8" />
  <text className="t m" x="460" y="201" textAnchor="middle" style={{ fontSize: 12 }}>OrderButton</text>
  <path className="line" d="M290 56 L170 96" /><path className="line" d="M330 56 L450 96" />
  <path className="line" d="M160 136 V176" /><path className="line" d="M460 136 V176" />
  <circle r="6" style={{ fill: "#7c3aed" }}><animate attributeName="cx" values="290;170;160" dur="2.4s" repeatCount="indefinite" /><animate attributeName="cy" values="56;96;176" dur="2.4s" repeatCount="indefinite" /></circle>
  <circle r="6" style={{ fill: "#ea580c" }}><animate attributeName="cx" values="460;450;330" dur="2.4s" begin="1.2s" repeatCount="indefinite" /><animate attributeName="cy" values="176;136;56" dur="2.4s" begin="1.2s" repeatCount="indefinite" /></circle>
  <text className="t" x="20" y="80" style={{ fontSize: 12, fill: "#7c3aed" }}>● data goes down</text>
  <text className="t" x="470" y="80" style={{ fontSize: 12, fill: "#ea580c" }}>● events go up</text>
</svg>
<figcaption>A component tree. Parameters flow down. Events flow up.</figcaption>
</figure>

**Simple lesson:** A parent uses a child. Data goes down, events go up.

## Component Parameters ([Parameter])

- A **parameter** is a value that the parent gives to the child. Think of the name and price printed on a menu card.
- The child **declares** the parameter: a `public` property with `[Parameter]` above it.
- The parent **sets** it, like an HTML attribute: `Name="Masala Tea"`.
- To pass a C# variable instead of fixed text, use `@`: `Price="@icedPrice"`.

In the below example, `TeaCard.razor` has three parameters: `Name`, `Price` and `IsHot`. `Menu.razor` uses it twice with different values. The second card gets its price from the C# variable `icedPrice`.

@code {
      private int icedPrice = 30;
}
`,
    "Components/TeaCard.razor": `<p>
      <b>@Name</b>: ₹@Price
      @(IsHot ? "🔥" : "🧊")
</p>

@code {
      [Parameter] public string Name { get; set; } = "";
      [Parameter] public int Price { get; set; }
      [Parameter] public bool IsHot { get; set; }
}
`,
  }}
/>

**What you see:** two lines made by the same `TeaCard`: "Masala Tea: ₹20 🔥" and "Iced Lemon Tea: ₹30 🧊". Try it: in `Menu.razor`, set `icedPrice` to `35` and press **▶ Run**.

A child should **not** change its own parameter values. The parent owns them. If the child needs a change, it tells the parent with an event (see **Child-to-Parent Communication (EventCallback)** below).

**Simple lesson:** Mark a public property with `[Parameter]`, then set it from the parent like an attribute.

## Required Parameters ([EditorRequired])

- Some parameters are a must. A tea card without a name makes no sense.
- Mark them with `EditorRequired` next to `Parameter`: `[Parameter, EditorRequired]`.
- If a parent forgets a required parameter, the editor shows a **yellow warning line**. The app still runs, but you see the mistake early.

In the below example, `TeaCard.razor` makes the `Name` parameter required. Since `Menu.razor` passes `Name="Masala Tea"`, no warning appears.

`,
    "Components/TeaCard.razor": `<p>Tea: @Name</p>

@code {
      [Parameter, EditorRequired]
      public string Name { get; set; } = "";
}
`,
  }}
/>

**Try it:** in `Menu.razor`, delete `Name="Masala Tea"` and wait a moment. A yellow line appears under `TeaCard`. Hover over it to read: "Component 'TeaCard' expects a value for the parameter 'Name'".

**Simple lesson:** `[EditorRequired]` warns you when the parent forgets an important parameter.

## Cascading Parameters ([CascadingParameter])

- A **cascading value** is a value that every component inside it can read, at any depth.
- The parent wraps components in `<CascadingValue Value="...">`.
- A child reads it with `[CascadingParameter]`.
- Use it for a value that many components need, like a theme colour.

<figure className="blz-fig">
<svg viewBox="0 0 600 200" role="img" aria-labelledby="fig-cb-cascade">
  <title id="fig-cb-cascade">Animation: a CascadingValue box with the value Green wraps three levels of components. A green wave flows down through all of them, so the deepest component also gets Green without the middle one passing it.</title>
  <rect x="20" y="16" width="560" height="170" rx="12" style={{ fill: "#dcfce7", stroke: "#16a34a", strokeWidth: 2 }}>
    <animate attributeName="opacity" values="0.4;1;0.4" dur="2.5s" repeatCount="indefinite" />
  </rect>
  <text className="t m" x="40" y="42" style={{ fontSize: 13, fontWeight: 700 }}>&lt;CascadingValue Value="Green"&gt;</text>
  <rect className="box" x="60" y="60" width="480" height="110" rx="10" />
  <text className="t m" x="80" y="84" style={{ fontSize: 12 }}>Menu</text>
  <rect className="box" x="100" y="96" width="400" height="62" rx="8" />
  <text className="t m" x="120" y="118" style={{ fontSize: 12 }}>TeaCard (does not pass anything)</text>
  <rect className="grn" x="300" y="124" width="180" height="28" rx="6" />
  <text className="t m" x="390" y="143" textAnchor="middle" style={{ fontSize: 12 }}>OrderButton gets Green</text>
</svg>
<figcaption>Every component inside CascadingValue can read the value, at any depth.</figcaption>
</figure>

In the below example, `Menu.razor` sends the colour `"green"` with `CascadingValue`. `TeaCard.razor` does not pass it on, but `OrderButton.razor` still gets it through `[CascadingParameter]`.

@code {
      private string themeColor = "green";
}
`,
    "Components/TeaCard.razor": `<p>@Name</p>

@code {
      [Parameter] public string Name { get; set; } = "";
}
`,
    "Components/OrderButton.razor": `<button style="background: @Color; color: white;">Order</button>

@code {
      [CascadingParameter] public string Color { get; set; } = "gray";
}
`,
  }}
/>

**What you see:** a green **Order** button, two levels below `Menu`, with no colour passed in between. Try it: change `"green"` to `"purple"` in `Menu.razor` and press **▶ Run**.

**Simple lesson:** `CascadingValue` shares one value with every component below it.

## Child Content (RenderFragment)

- **Child content** lets the parent put its own HTML inside a child component.
- The parent writes the HTML between the child's tags: `<Panel>` ... `</Panel>`.
- The child gets it in a parameter named `ChildContent`, and shows it with `@ChildContent`.

**RenderFragment** = the type of `ChildContent`. It is a piece of HTML kept in a variable, ready to show later.

In the below example, `Panel.razor` draws the purple border and the title, and shows the parent's HTML at `@ChildContent`. `Home.razor` uses it twice with different HTML inside.

      <p>Masala Tea with ginger. Only <b>₹20</b>!</p>

      <p>7 AM to 9 PM, every day.</p>
`,
    "Components/Panel.razor": `<div style="border: 2px solid #6d28d9; border-radius: 8px; padding: 8px; margin: 8px 0;">
      <h4 style="margin: 0;">@Title</h4>
      @ChildContent
</div>

@code {
      [Parameter] public string Title { get; set; } = "";
      [Parameter] public RenderFragment? ChildContent { get; set; }
}
`,
  }}
/>

**What you see:** two cards with the **same** purple style but **different** content. The style comes from `Panel.razor`. The content comes from `Home.razor`. Try it: add `<p>Free Wi-Fi!</p>` inside the second panel and press **▶ Run**.

**Simple lesson:** Add a `RenderFragment ChildContent` parameter, and the parent can put any HTML inside your component.

## Child-to-Parent Communication (EventCallback)

- Parameters send data **down**, from parent to child. But a child, like a button, often needs to tell its parent "I was clicked".
- A child must not change the parent's data directly. Instead, it **raises an event**, and the parent decides what to do.
- The child has a parameter of type `EventCallback`. Use `EventCallback<T>` to send a value of type `T` with the event.

In the below example, `OrderButton.razor` sends the tea name up with `OnOrder.InvokeAsync(Tea)`. `Menu.razor` connects it to `AddOrder`, which adds the tea to its list.

<ul>
      @foreach (var tea in orders)
      {
          <li>@tea</li>
      }
</ul>

@code {
      private List<string> orders = new();

      private void AddOrder(string tea)
      {
          orders.Add(tea);
      }
}
`,
    "Components/OrderButton.razor": `<button @onclick="Order">Order @Tea</button>

@code {
      [Parameter] public string Tea { get; set; } = "";
      [Parameter] public EventCallback<string> OnOrder { get; set; }

      private async Task Order()
      {
          await OnOrder.InvokeAsync(Tea);
      }
}
`,
  }}
/>

**What you see:** click **Order Masala Tea** two times and **Order Ginger Tea** once. The parent shows **Orders: 3** and lists all three teas.

**Simple lesson:** The child raises an `EventCallback`. The parent handles it and updates its own data.

## Styling Components

There are four ways to add CSS to a Blazor component. They differ in **where** the styles apply.

| Way | Where you write it | Where it applies |
|---|---|---|
| Inline styling | `style="..."` on one element | That one element |
| Internal styling | A `<style>` block in the `.razor` file | The whole page, while the component is shown |
| Component-scoped styles | `TeaCard.razor.css` | Only that component |
| Application-wide styles | `wwwroot/app.css` | Every page of the app |

### Inline Styling

- Write CSS straight on an element with the `style` attribute: `<p style="color: green;">`.
- It is quick for one small change.
- You can use C# in it: `style="color: @color;"`.

In the below example, the price uses a fixed inline style. The tea name gets its colour from the C# variable `color`.

<p style="color: gray;">Only ₹20</p>

<button @onclick='() => color = "purple"'>Make it purple</button>

@code {
      private string color = "green";
}
`,
  }}
/>

### Internal Styling

- Write CSS rules in a `<style>` block inside the `.razor` file.
- It keeps the styles next to the HTML that uses them.
- Careful: these rules are **not** limited to the component. They affect the **whole page** while the component is shown. Use class names that are unlikely to clash, like `.tea-card`.

In the below example, the `<style>` block styles the `.tea-card` class. Both cards use it.

      .tea-card {
          border: 2px solid #6d28d9;
          border-radius: 8px;
          padding: 8px;
          margin: 6px 0;
      }
</style>

<div class="tea-card">Masala Tea: ₹20</div>
<div class="tea-card">Ginger Tea: ₹25</div>
`,
  }}
/>

### Component-Scoped Styles (.razor.css)

- Put the component's CSS in a file with the same name plus `.css`: `TeaCard.razor.css`, next to `TeaCard.razor`.
- These styles apply **only** to that component. A `p` rule here does not change any other page.
- This is also called **CSS isolation**. It is the best choice for most component styles.

In the below example, `TeaCard.razor.css` makes paragraphs purple. Only the paragraph inside `TeaCard` turns purple. The paragraph in `Menu.razor` stays black.

      <p>@Name</p>
</div>

@code {
      [Parameter] public string Name { get; set; } = "";
}
`,
    "Components/Pages/Menu.razor": `@page "/menu"

<p>This paragraph is in Menu.razor, so it stays black.</p>
`,
  }}
/>

### Application-Wide Styles (app.css)

- Styles that every page needs, like the font or the colour of all headings, go in one file: `wwwroot/app.css`.
- `App.razor` loads it for the whole app with `<link rel="stylesheet" href="@Assets["app.css"]" />`.
- Older Blazor templates called this file `site.css`. It does the same job.

In the below example, `app.css` sets the font and makes every `h2` green. Both the page and the `ShopFooter` component follow it.

<p>Fresh tea, made to order.</p>

`,
    "Components/ShopFooter.razor": `<h2>Visit us</h2>
<p>Open 7 AM to 9 PM.</p>
`,
  }}
/>

Edit a `.css` file, then press **▶ Run** to see the change. In your own project, Hot Reload updates CSS as soon as you save.

**Simple lesson:** Use inline styles for one element, `.razor.css` for one component, and `app.css` for the whole app. Internal `<style>` blocks affect the whole page.

## Common mistakes

<div className="tscroll">

| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
| Naming a component `teaCard.razor` | Any name works | Start with a capital letter: `TeaCard.razor` | `<teaCard />` is treated as an unknown HTML tag |
| Forgetting `[Parameter]` | Any public property can be set by the parent | Add `[Parameter]` above it | An error: the component has no such parameter |
| Changing a parameter inside the child | The child owns its parameters | The parent owns them. Raise an `EventCallback` | The parent's next render overwrites the change |
| Calling the parameter `Content` instead of `ChildContent` | Any name receives the inner HTML | Name it exactly `ChildContent` | The HTML between the tags is not shown |
| Forgetting `InvokeAsync` in the child | Declaring `EventCallback` is enough | Call `await OnOrder.InvokeAsync()` | The parent never hears about the click |
| Expecting a `<style>` block to stay in one component | Internal styles are scoped | Use `Name.razor.css` for scoped styles | Other components change too |

</div>

## Check Yourself

## Exercises

## What to Remember

- A component is one `.razor` file. Its name starts with a capital letter. Use it like a tag: `<TeaCard />`.
- `[Parameter]` passes data **down**. `[EditorRequired]` warns when a parameter is missing.
- `CascadingValue` shares one value with every component below.
- `RenderFragment ChildContent` lets the parent put HTML inside.
- `EventCallback` sends messages **up** to the parent.
- Style with inline `style`, a `<style>` block, `Name.razor.css` (only that component) or `app.css` (the whole app).

Next: **Built-in Components**
