use_textarea_autosize
Automatically update the height of a textarea depending on the content.
Demo
Usage
Simple example
use leptos::prelude::*;
use leptos::html::Textarea;
use leptos_use_textarea_autosize::{use_textarea_autosize, UseTextareaAutosizeReturn};
#[component]
fn Demo() -> impl IntoView {
let textarea = NodeRef::new();
let UseTextareaAutosizeReturn {
content,
set_content,
trigger_resize
} = use_textarea_autosize(textarea);
view! {
<textarea
prop:value=content
on:input=move |evt| set_content.set(event_target_value(&evt))
node_ref=textarea
class="resize-none"
placeholder="What's on your mind?"
/>
}
}
Make sure that you set
box-sizing: border-boxon the textarea element.It’s also recommended to reset the scrollbar styles for the textarea element to avoid incorrect height values for large amounts of text.
#![allow(unused)]
fn main() {
textarea {
-ms-overflow-style: none;
scrollbar-width: none;
}
textarea::-webkit-scrollbar {
display: none;
}
}
With rows attribute
If you need support for the rows attribute on a textarea element, then you should set the
style_prop option to "min-height".
use leptos::prelude::*;
use leptos::html::Textarea;
use leptos_use_textarea_autosize::{use_textarea_autosize_with_options, UseTextareaAutosizeOptions, UseTextareaAutosizeReturn};
#[component]
fn Demo() -> impl IntoView {
let textarea = NodeRef::new();
let UseTextareaAutosizeReturn {
content,
set_content,
..
} = use_textarea_autosize_with_options(
textarea,
UseTextareaAutosizeOptions::default().style_prop("min-height"),
);
view! {
<textarea
prop:value=content
on:input=move |evt| set_content.set(event_target_value(&evt))
node_ref=textarea
class="resize-none"
placeholder="What's on your mind?"
rows="3"
/>
}
}
SendWrapped Return
The returned closure trigger_resize is a sendwrapped function. It can
only be called from the same thread that called use_textarea_autosize.
Server-Side Rendering
Make sure you follow the instructions in Server-Side Rendering.
On the server this will always return an empty string as ´contentand a no-optrigger_resize`.
Installation
cargo add leptos-use-textarea-autosize
Options
UseTextareaAutosizeOptions
Options for use_textarea_autosize_with_options.
Every option is set with a builder method of the same name, e.g. UseTextareaAutosizeOptions::default().content(...). See also the API docs.
content
Type: MaybeRwSignal<String>
Textarea content
watch
Type: Arc<dyn Fn() + Send + Sync>
Watch sources that should trigger a textarea resize
on_resize
Type: Arc<dyn Fn() + Send + Sync>
Function called when the textarea size changes
style_target
Type: ElementMaybeSignal<web_sys::Element>
Specify style target to apply the height based on textarea content. If not provided it will use textarea it self.
style_prop
Type: String
Specify the style property that will be used to manipulate height.
Should be "height" or "min-height". Default value is "height".