Skip to content

useTextareaAutosize ​

Category
Export Size
869 B
Last Changed
last week

Automatically update the height of a textarea depending on the content.

Demo ​

Type, the textarea will grow:

Usage ​

Simple example ​

vue
<script setup lang="ts">
const { textarea, input } = useTextareaAutosize()
</script>

<template>
  <textarea
    ref="textarea"
    v-model="input"
    class="resize-none"
    placeholder="What's on your mind?"
  />
</template>

INFO

It's recommended to reset the scrollbar styles for the textarea element to avoid incorrect height values for large amounts of text.

css
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 styleProp option to minHeight.

vue
<script setup lang="ts">
const { textarea, input } = useTextareaAutosize({ styleProp: 'minHeight' })
</script>

<template>
  <textarea
    ref="textarea"
    v-model="input"
    class="resize-none"
    placeholder="What's on your mind?"
    rows="3"
  />
</template>

Type Declarations ​

typescript
export interface UseTextareaAutosizeOptions {
  /** Textarea element to autosize. */
  element?: MaybeRef<HTMLTextAreaElement | undefined>
  /** Textarea content. */
  input?: MaybeRef<string | undefined>
  /** Watch sources that should trigger a textarea resize. */
  watch?: WatchSource | Array<WatchSource>
  /** Function called when the textarea size changes. */
  onResize?: () => void
  /** Specify style target to apply the height based on textarea content. If not provided it will use textarea it self.  */
  styleTarget?: MaybeRef<HTMLElement>
  /** Specify the style property that will be used to manipulate height. Can be `height | minHeight`. Default value is `height`. */
  styleProp?: "height" | "minHeight"
}
export declare function useTextareaAutosize(
  options?: UseTextareaAutosizeOptions,
): {
  textarea: Ref<HTMLTextAreaElement>
  input: Ref<string>
  triggerResize: () => void
}
export type UseTextareaAutosizeReturn = ReturnType<typeof useTextareaAutosize>

Source ​

Source • Demo • Docs

Contributors ​

Anthony Fu
yakudik
leex
JD Solanki
Dominik Pschenitschni
Jelf
Enzo Innocenzi

Changelog ​

v10.8.0 on 2/20/2024
5025e - feat: allow configuring styleProp to support native rows attribute (#3552)
v10.2.0 on 6/16/2023
1b0ec - fix: autosize error when changing input asynchronously (#3118)
v10.0.0-beta.0 on 3/14/2023
a3e95 - feat: added styleTarget option to style other element (#2312)
v9.7.0 on 12/16/2022
ea497 - fix: reference
ebd48 - fix: support changes of element width (#2541)

Released under the MIT License.