Form control

Import
import { FormControl, useFormControl } from "reshaped";
import type { FormControlProps } from "reshaped";

FormControl provides a wrapper and separate components for the form field label, helper text, and status captions. When used together with input components provided by Reshaped, those components will automatically use the context data from FormControl.

<FormControl>
  <FormControl.Label>Favorite fruit:</FormControl.Label>
  <TextField name="fruit" />
  <FormControl.Helper>Melons are berries</FormControl.Helper>
</FormControl>

By default, FormControl works with single fields, but it can be used for input groups with the group property. This converts FormControl to a fieldset, providing better accessibility for your grouped form elements. It's handy when you need a label for a group of Radio or Checkbox fields.

<FormControl group>
  <FormControl.Label>Favorite animals:</FormControl.Label>

  <RadioGroup name="animalGroup">
    <View gap={2}>
      <Radio value="dog">Dog</Radio>
      <Radio value="cat">Cat</Radio>
    </View>
  </RadioGroup>
</FormControl>

FormControl provides success and error statuses, which control the rendering of error/success messages and allow you to change input styles based on the current status. Error and success messages render only when their status is active, but the helper message is rendered by default. To hide the helper message when the input status changes, use conditional rendering based on the status.

<FormControl hasError>
  <FormControl.Label>Favorite fruit:</FormControl.Label>
  <TextField name="fruit" />
  <FormControl.Helper>Melons are berries</FormControl.Helper>
  <FormControl.Error>This field is required</FormControl.Error>
</FormControl>

FormControl comes in two sizes, with medium as the default. Use large with larger input sizes to align the text size.

<FormControl size="large">
  <FormControl.Label>Favorite fruit</FormControl.Label>
  <TextField name="fruit" value="Apple" size="xlarge" />
  <FormControl.Helper>Melons are berries</FormControl.Helper>
</FormControl>

When using FormControl to render custom-built input fields, get all the context data with the useFormControl hook. All properties provided by useFormControl can be found in its documentation.

function Example() {
  const CustomInput = () => {
    const { attributes } = useFormControl();

    return <input {...attributes} type="text" />;
  };

  return (
    <FormControl>
      <FormControl.Label>Label</FormControl.Label>
      <CustomInput />
      <FormControl.Helper>Caption</FormControl.Helper>
    </FormControl>
  );
}
  • FormControl provides all attributes required by accessibility standards to the wrapped elements. They are passed to the Reshaped input components by default, but ensure all of them are used when building custom input components.