Skip to content

Latest commit

 

History

History
423 lines (317 loc) · 16.2 KB

components.md

File metadata and controls

423 lines (317 loc) · 16.2 KB

Components

Astro docs: Components

An AstroSharp component is an ordinary Razor component — a .razor file, rendered through Blazor's static HtmlRenderer. Existing .razor editor tooling works on it unchanged.

Where the limits actually are

Almost everything this page calls a limitation is a property of one boundary: the one between .astro and C#. Props cross it as JSON, over a process boundary, which is why a Map flattens and a function needs a stand-in.

Between two .razor components there is no boundary at all. Your components are compiled together by Roslyn into one assembly and rendered by one HtmlRenderer, so composing them is ordinary Blazor:

@* Nothing is serialized here. These are C# objects being passed to a C# method. *@
<ProductCard Product="_product"
             Formatter="@(p => p.Price.ToString("C"))"
             Tags="_tagLookup"
             OnSale="_saleEnds > DateTime.UtcNow" />

A Func<>, a Dictionary<,>, an interface, a record with behaviour on it, a CancellationToken, an injected service — all of it passes as itself, with its type and its identity intact, because none of it goes anywhere. EventCallback, generic components, @typeparam, cascading values and RenderFragment<T> all work as they do in any Blazor project.

So if you are using Astro as the site builder and authoring your UI in Razor, most of what follows never comes up. Read it when you start mixing: an .astro page passing props into C#, or a C# component placing an .astro one. That seam is where the rules live, and it is the only place they apply.

Props and slots

---
// src/components/Card.astro
const { title, class: className } = Astro.props;
---
<article class:list={['card', className]}>
  <h2>{title}</h2>
  <div><slot /></div>
  <footer><slot name="footer" /></footer>
</article>
@* src/components/Card.razor *@
@code {
    [Parameter] public string Title { get; set; } = "";
    [Parameter] public string? Class { get; set; }
    [Parameter] public RenderFragment? ChildContent { get; set; }
    [Parameter] public RenderFragment? Footer { get; set; }
}

<article class="card @Class">
  <h2>@Title</h2>
  @if (ChildContent is not null) { <div>@ChildContent</div> }
  @if (Footer is not null) { <footer>@Footer</footer> }
</article>

Both are used identically:

---
import Card from '../components/Card.razor';
---
<Card title="Hello" class:list={['wide', { featured: true }]}>
  <p>Default slot content.</p>
  <span slot="footer">Named slot content.</span>
</Card>

Props are [Parameter] properties, bound by name, case-insensitively. The default slot binds to ChildContent; a named slot binds to a RenderFragment parameter of the same name, or that name plus Content. class:list arrives as an ordinary computed class prop.

Props the parameter list does not name

---
// src/components/Field.astro
const { label, ...rest } = Astro.props;
---
<input {...rest} aria-label={label} />
@* src/components/Field.razor *@
@code {
    [Parameter] public string Label { get; set; } = "";

    [Parameter(CaptureUnmatchedValues = true)] public IDictionary<string, object>? Rest { get; set; }
}

<input @attributes="Rest" aria-label="@Label" />

CaptureUnmatchedValues is Blazor's own ...rest, filled from the .astro boundary as well as from a .razor parent. A caller can pass class, id, data-* and aria-* through a component that knows nothing about them:

<Field label="Email" class="wide" data-track="signup" required={true} />

Each JSON shape becomes the attribute Astro's own {...rest} would have written: a string as itself, a number invariantly, true as a bare boolean attribute, and false or null as no attribute at all. Without a capture parameter, a prop nothing declares is dropped — which is what an .astro component does with one it never spreads.

Astro.Slots mirrors Astro.slots for inspection:

@if (Astro.Slots.Has("footer")) { <hr /> }

Using an .astro component from C#

Two steps, the same two an .astro file takes: import it, then place it.

---
import Badge from './Badge.astro';
---
<Badge label="new" tone="warn">
  <em>This becomes the default slot.</em>
</Badge>
@{ var badge = Astro.Import("./Badge.astro"); }

<AstroComponent Ref="@badge" Props='new { label = "new", tone = "warn" }'>
  <em>This becomes the default slot.</em>
</AstroComponent>

Nothing is declared. The path is a compile-time literal, so the build reads it out of the call and generates a real import. Vite then sees the component, and its scoped styles reach the page as usual. This is a rendered component, not interpolated markup.

Props is an ordinary object, serialized for you. It travels as JSON beside a placeholder token rather than through the markup, so quotes and angle brackets in a value need no escaping. Note the single quotes around it: Razor ends a double-quoted attribute at the first inner double quote, and these expressions usually contain strings.

For a placement with no children, render the import directly — which reads closest to the .astro tag it stands for, and keeps naming the module and using it in the order they are written:

@{ var badge = Astro.Import("./Badge.astro"); }

@badge.Render(new { label = "new", tone = "warn" })

Astro.Component(badge, new { label = "new" }) is the same thing said the other way round, and reads better when the ref is an expression rather than a name:

@Astro.Component(expanded ? detail : summary, new { id })

Both take head: for output bound for the document head. Neither can carry children — slot content is markup the page renders between two markers, which a method returning one value cannot express, so that stays the <AstroComponent> element above.

Head-bound components

A component whose output belongs in the document head — <ClientRouter />, <Font />, anything emitting <meta> or <link> — sets Head:

@{
    var router = Astro.Import("astro:transitions", export: "ClientRouter");
    var seo = Astro.Import("../components/Seo.astro");
}

@router.Render(head: true)
<AstroComponent Ref="@seo" Head Props='new { description = "..." }' />

The output lands in <head> rather than where the element sits. A page that renders its own document has it spliced into that </head>. A page with a layout goes through Astro's head propagation, arriving with the layout's own head content — scripts bundled, styles hoisted.

Astro.Import

The .razor equivalent of an import statement. It is written as its own line, like the import it stands for, and what it returns carries the module to wherever it is used:

---
import Card from '../components/Card.astro';
import hero from '../assets/hero.png';
---
<Card image={hero} />
@{
    var card = Astro.Import("../components/Card.astro");
    var hero = Astro.Import("../assets/hero.png");
}

<AstroComponent Ref="card" Props='new { image = hero }' />

Nothing is declared — the path is a literal, so the build reads it out of the call and generates a real import.

Ref versus Src. Src is the path written on the tag; Ref is a binding chosen in C#. Only Ref can express a choice the markup does not make:

@{
    var summary = Astro.Import("./Summary.astro");
    var detail = Astro.Import("./Detail.astro");
}

<AstroComponent Ref="@(expanded ? detail : summary)" />

Both name the same thing — a key the generated module registered an import under — so setting both is an error rather than a precedence rule.

As a prop, an import is the only way to pass a value Astro's own components want: props travel as JSON, so a module binding cannot travel as itself. It works anywhere in the props object, including inside an array or a nested object.

Hydrating a placed component

An .astro component cannot hydrate — that is Astro's own rule — but a framework component placed from C# can. The directive goes on the import:

---
import Counter from '../components/Counter.svelte';
---
<Counter client:visible start={5} />
@{ var counter = Astro.Import("../components/Counter.svelte", client: "visible"); }

<AstroComponent Ref="@counter" Props='new { start = 5 }' />

You get a real island: Astro's own <astro-island> element, its client runtime, and the component emitted into the client bundle.

Nothing privileged is happening. Astro's compiler passes client:visible, client:component-path and client:component-export to renderComponent as ordinary props; all three are knowable at build time, so the build reads them out of the import and the placement passes the same ones.

Why the import and not the tag. The directive has to sit where the build can see it, and the import is the one call that names the component. A placement can still choose a different directive to wake on, because that part is only props:

<AstroComponent Ref="@counter" Client="idle" Props='new { start = 5 }' />

client takes load, idle, visible, media or only, and clientValue carries the argument — the media query for media, the framework name for only:

@{ var wide = Astro.Import("./Wide.svelte", client: "media", clientValue: "(min-width: 50em)"); }

Astro's own components

<Image>, <Picture> and <Font> are generated into every project as .razor components, so they read the way they do in an .astro file:

---
import { Image } from 'astro:assets';
import hero from '../assets/hero.png';
---
<Image src={hero} width={400} format="webp" alt="A hero" class="rounded" />
@{ var hero = Astro.Import("../assets/hero.png"); }

<Image Ref="@hero" Width="400" Format="webp" Alt="A hero" class="rounded" />

They are Astro's components, unmodified — the generated .razor file is a parameter list over a placement of the real export.

Ref and Src are Astro's own either/or, made explicit. Ref takes an import, which is what these components need — they want the ImageMetadata, not a path. Src takes a literal URL or /public path, which nothing imports and which is passed along as written:

<Image Src="https://cdn.example.com/hero.png" Alt="Remote" Width="800" Height="600" />

Anything the parameter list does not name — class, id, style — is forwarded to the tag as written.

See Images and Fonts for what each one takes.

There is nothing special about them: each is an ordinary Astro.Import of astro:assets, and any other component one of Astro's modules exports is reached the same way.

@{ var router = Astro.Import("astro:transitions", export: "ClientRouter"); }

@Astro.Component(router, head: true)

Namespacing

Components are namespaced by their folder, so components/Card.razor and ui/Card.razor do not collide. A file that declares its own @namespace is honoured; discovery is by interface or class, never by a required namespace.

What a prop from .astro can be

This section is about the boundary only. A prop passed from one .razor component to another is an ordinary C# argument and none of it applies — see Where the limits actually are.

Props from an .astro file are JSON on the wire, because they cross a process boundary. Anything JSON expresses arrives as itself; anything else arrives as its JSON shadow:

Passed from .astro Arrives in C# as
string, number, boolean, array, plain object itself
Date an ISO string — take it as DateTime, which binds from one
Map, Set {} — pass an object or an array instead
undefined property absent, leaving the [Parameter] at its default
a function a stand-in, resolved into the markup after the render — see below
an Error AstroErrorInfo — Name, Message, Stack, Cause
a class instance its own properties, without its prototype
BigInt, a circular reference a build failure, naming the component and the prop

The last row is the only one that stops a build, and deliberately: JSON.stringify throws on both, and its own message names neither the component nor the prop, which leaves nowhere to look.

An Error is the row that would otherwise be a lie. It is a class instance, and its message and stack are own but non-enumerable, so JSON.stringify(new Error('boom')) is {} — the prop would arrive holding nothing at all. It is given an enumerable shape on the way across instead, including a cause, which matters most for 500.razor, where the error prop is the only thing the page has to say.

A function prop

A function cannot be JSON, so it arrives as a stand-in and its real value is substituted into the markup after the render — the same mechanism Module.Defer uses. It can be written, but not computed with:

@* Fine: written straight into the markup. *@
<p>@Greeting</p>

@* Not fine: the value does not exist yet, so this measures the stand-in. *@
@if (Greeting!.Length > 50) { <p>Wordy</p> }

Lazily, too: the function runs only if its stand-in reached the output, so a callback nothing renders is never called. That is the reason for deferring rather than calling every function prop up front — someone else's callback may be expensive, and is not ours to run speculatively.

The substituted value is escaped, as interpolating a string is. For one that is HTML, ask for it as markup:

<div>@Astro.RawHtml(Markup)</div>

Astro.RawHtml returns anything that is not one of these stand-ins unchanged, so it is not a general "trust this string" switch — for an ordinary value that is already HTML, @((MarkupString)value) is still the cast.

The exception is Astro's Markdown layout contract. rawContent() and compiledContent() are called before the render and arrive as real strings, because both are cheap pure reads and a layout has every reason to compute with them. See Markdown.

Two shapes of value have their own pages. An import is a module binding: it cannot travel as JSON, so it is passed as a reference the build resolves. A framework component cannot travel at all.

Limitations

No hydration. See Islands architecture. A client:* directive fails the build.

A placed .astro component cannot hydrate, because Astro does not hydrate .astro components at all. A framework component placed from C# does — see Hydrating a placed component.

An import of a file has to be written in the .razor file that .astro imports. The generated import goes into that file's compiled module, and a nested .razor component has no module of its own in the page's graph. An import of a module — astro:assets, astro:transitions — is registered project-wide, so <Image> and <Font> work at any depth.

A path, and a client: directive, have to be literals. The build reads them out of the call, and Vite resolves imports statically, so neither can be computed at runtime. A non-literal path fails the build saying so.

A C# component cannot reach the head of the .astro page using it. There is no factory of AstroSharp's in that tree to propagate from, so it emits where it stands. Mark head content on the C# page, or put it in the layout.

Scoped slots are not supported. Astro pre-renders slots to HTML before C# sees them, so there is nothing to pass an argument into.

A function prop cannot be stored, transformed or passed on. It is a stand-in until the render is over, so holding one in a field, measuring it, or passing it on all fail. The last fails loudly: a stand-in that reaches the output is caught and reported rather than shipped as gibberish.

A function prop is called with no arguments, so a callback that needs one has nothing to give it. There is no seam for C# to call back into an .astro page's closure mid-render.

No .cshtml, and no Astro-shaped C# syntax. Components are .razor.