f6ae86617c
Co-authored-by: Copilot <copilot@github.com>
6.4 KiB
6.4 KiB
Textarea
A styled multi-line text input. Use it when you need more than a single line of text — comments, descriptions, notes, bio fields, or message composition.
Quick example
new Textarea(
id: "comment",
name: "comment",
placeholder: "Write a comment…",
label: "Comment",
rows: 5)
All the options
public Textarea(
string id,
string name = "",
string placeholder = "",
string label = "",
string description = "",
string defaultValue = "",
string extraClasses = "",
string hxAttrs = "",
int rows = 3)
| Parameter | What it does |
|---|---|
id |
The element id. Also used by the <label for="...">. |
name |
Form field name. |
placeholder |
Greyed-out hint inside the field when it is empty. |
label |
Visible text label above the field. |
description |
Small hint below the field (e.g. character limits). |
defaultValue |
Pre-filled content. |
extraClasses |
Additional Tailwind classes on the <textarea>. |
hxAttrs |
Extra HTML attributes appended verbatim. |
rows |
How many lines tall the field is initially. Default is 3. |
Real-world examples
Bio field (editing an existing value)
new Textarea(
id: "bio",
name: "bio",
label: "Bio",
description: "Max 280 characters",
defaultValue: System.Web.HttpUtility.HtmlEncode(user.Bio ?? ""),
rows: 4)
Auto-growing field (expands as the user types)
Pass a small oninput handler through hxAttrs:
new Textarea(
id: "notes",
name: "notes",
label: "Notes",
rows: 3,
hxAttrs: """oninput="this.style.height=''; this.style.height=this.scrollHeight+'px'"""")
Reading on the server
public record Command(
[property: FromForm] string Bio
);
How it works
Textarea renders a standard HTML <textarea> element. The defaultValue is placed between the opening and closing tags (not in value like an <input>). Always HTML-encode any user-supplied defaultValue before passing it in.
new Textarea(
id: "draft",
name: "content",
label: "Draft",
hxAttrs: """hx-post="/drafts/save" hx-trigger="keyup changed delay:500ms" hx-include="[name='content']"""")
### Reading in a form handler
```csharp
public record Command([property: FromForm] string Comment);
// command.Comment contains the textarea value
Tips and tricks
- HTML-encode the
defaultValueif it contains user-supplied content — it is placed directly inside the<textarea>element. rowscontrols the initial visible height but the user can resize vertically. For a fixed-height textarea, addresize-noneinextraClasses.- For a character counter, add
maxlengthviahxAttrsand pair with a small JS snippet or a sibling<span>updated oninput. placeholdertext is not submitted — always usedefaultValuefor edit forms where existing content should be pre-filled.placeholdertext is not submitted — always usedefaultValuefor edit forms where existing content should be pre-filled.
Complete page example
Templates/FeedbackPage.htmx
<div class="max-w-lg mx-auto py-10">
<h1 class="text-2xl font-bold mb-2">Send feedback</h1>
<p class="text-sm text-muted-foreground mb-6">We read every message.</p>
<form method="post" action="/feedback">
$$AntiforgeryToken$$
<div class="space-y-5 mb-6">
$$SubjectInput$$
$$MessageArea$$
</div>
$$SubmitBtn$$
</form>
$$SuccessAlert$$
</div>
Templates/FeedbackPage.htmx.cs
namespace Htmx.ApiDemo.Templates;
public sealed class FeedbackPage : FeedbackPageBase
{
private readonly IHtmxComponent _subject;
private readonly IHtmxComponent _message;
private readonly IHtmxComponent _submit;
private readonly IHtmxComponent _success;
private readonly byte[] _afToken;
public FeedbackPage(
IAntiforgery af,
HttpContext ctx,
string subjectError = "",
string messageError = "",
bool submitted = false)
{
var tokens = af.GetAndStoreTokens(ctx);
_afToken = $"""<input type="hidden" name="{tokens.FormFieldName}" value="{tokens.RequestToken}">""".ToUtf8Bytes();
_subject = new Components.Input(
id: "subject",
name: "subject",
label: "Subject",
placeholder: "What's on your mind?",
errorMessage: subjectError);
_message = new Components.Textarea(
id: "message",
name: "message",
label: "Message",
rows: 6,
placeholder: "Describe your feedback in detail…",
errorMessage: messageError);
_submit = new Components.Button("Send feedback", type: "submit");
_success = submitted
? new Components.Alert(title: "Thank you!", description: "Your feedback has been received.")
: HtmxEmpty.Instance;
}
protected override void RenderAntiforgeryToken(HtmxRenderContext ctx) => ctx.Writer.WriteUtf8(_afToken);
protected override void RenderSubjectInput(HtmxRenderContext ctx) => _subject.Render(ctx.Next());
protected override void RenderMessageArea(HtmxRenderContext ctx) => _message.Render(ctx.Next());
protected override void RenderSubmitBtn(HtmxRenderContext ctx) => _submit.Render(ctx.Next());
protected override void RenderSuccessAlert(HtmxRenderContext ctx) => _success.Render(ctx.Next());
}
POST handler
[Handler]
[MapPost("/feedback")]
public static partial class PostFeedbackHandler
{
public record Command(
[property: FromForm] string Subject,
[property: FromForm] string Message);
private static Task<IResult> HandleAsync(
[AsParameters] Command cmd, HttpContext ctx, IAntiforgery af, CancellationToken ct)
{
if (string.IsNullOrWhiteSpace(cmd.Subject))
return ctx.WriteHtmxPage(
new FeedbackPage(af, ctx, subjectError: "Subject is required."), title: "Feedback");
if (string.IsNullOrWhiteSpace(cmd.Message))
return ctx.WriteHtmxPage(
new FeedbackPage(af, ctx, messageError: "Message is required."), title: "Feedback");
// Persist feedback…
return ctx.WriteHtmxPage(
new FeedbackPage(af, ctx, submitted: true), title: "Feedback");
}
}
AppJsonSerializerContext.cs
[JsonSerializable(typeof(PostFeedbackHandler.Command), TypeInfoPropertyName = "FeedbackCommand")]