Components Basics

By Syncfusion®, Inc. · Last updated

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.

What you will learn

  • Create a component and use it in a page
  • Pass data down with [Parameter] and [CascadingParameter]
  • Accept child content with RenderFragment
  • Send events up with EventCallback
  • Style one component with 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.

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.

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.

1. Click cups++

2. Render again compare old and new

3. Browser page

Order your tea (same)

Cups: 2 (updated)

Add cup button (same)

Blazor renders the component again, then changes only what is different.

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.

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.
  • 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.

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.

Menu (parent)

TeaCard

TeaCard

OrderButton

OrderButton

● data goes down ● events go up

A component tree. Parameters flow down. Events flow up.

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.

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.

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.

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.

<CascadingValue Value="Green">

Menu

TeaCard (does not pass anything)

OrderButton gets Green

Every component inside CascadingValue can read the value, at any depth.

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].

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.

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.

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.

WayWhere you write itWhere it applies
Inline stylingstyle="..." on one elementThat one element
Internal stylingA <style> block in the .razor fileThe whole page, while the component is shown
Component-scoped stylesTeaCard.razor.cssOnly that component
Application-wide styleswwwroot/app.cssEvery 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.

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.

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.

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.

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

MistakeWrong ideaCorrect ideaWhat goes wrong
Naming a component teaCard.razorAny name worksStart with a capital letter: TeaCard.razor<teaCard /> is treated as an unknown HTML tag
Forgetting [Parameter]Any public property can be set by the parentAdd [Parameter] above itAn error: the component has no such parameter
Changing a parameter inside the childThe child owns its parametersThe parent owns them. Raise an EventCallbackThe parent's next render overwrites the change
Calling the parameter Content instead of ChildContentAny name receives the inner HTMLName it exactly ChildContentThe HTML between the tags is not shown
Forgetting InvokeAsync in the childDeclaring EventCallback is enoughCall await OnOrder.InvokeAsync()The parent never hears about the click
Expecting a <style> block to stay in one componentInternal styles are scopedUse Name.razor.css for scoped stylesOther components change too

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