A TextArea is an input field that allows the user to enter more than one line of text.
Note: the HTML element is called "textarea", one word — but the React component is "TextArea", as if it were two words.
Usage
Our Textarea component uses the native HTML <textarea>
input, so it can use the various properties of the native element, including the rows
property to control the textarea's default height.
Resizing
By default, users can resize the Textarea both vertically and horizontally. If you want to limit resizing to the vertical axis, you can add the "resize vertical" option:
This pairs well with the "full width" option, which makes the component take up all available width:
Labels, Errors, and Helper Text
Use skin="error"
for when the current value is invalid:
In React, when you use a TextArea
inside a FormField
along with other components, the "error" skin will be automatically applied when a FormError
component is present. You'll get some other convenience behaviors, including the textarea's label automatically having its for
attribute associated with the input. Refer to Form for more.
In vanilla, you can get the error skin by applying the class swan-textarea-skin-error
to the input.
Managing State
As is the case with most form elements, folks often want to "control" this component. Controlling a component means that you take ownership over its state rather than letting the browser manage the state for you. When you control component, you own the source of truth for the UI. This means that you don't need to query the DOM in order to determine the current value of the element. So, when it comes time to use the value of the element somewhere else (e.g. submitting the value to a back-end service) you can trust your stored state.
If you'd like to control a TextArea
, you'll need store the current value somewhere (e.g. React state or a Redux store), and you'll need to provide a handler to update that value when the user interacts with the component.
e.g.
The preview has been updated.
If you don't care about the state of the TextArea
, you can simply omit the value
and onChange
props. In this case, you may add the defaultValue
prop in order to specify the initial value of the TextArea
without committing to fully managing the state.