DXC Logo

Text input

Text inputs are fields commonly used in forms to capture user-entered text in a structured and accessible format.

Props

NameTypeDescriptionDefault
New
alignment
'left' | 'right'Sets text-align CSS property inside the input. See MDN for further information.'left'
action
{ icon?: string | (React.ReactNode & React.SVGProps<SVGSVGElement>); onClick: () => void; title?: string; }
Action to be displayed on the right side of the input.-
ariaLabelstringSpecifies a string to be used as the name for the textInput element when no label is provided.'Text input'
autocompletestringHTML autocomplete attribute. Lets the user specify if any permission the user agent has to provide automated assistance in filling out the input value. Its value must be one of all the possible values of the HTML autocomplete attribute. See MDN for further information.'off'
clearablebooleanIf true, the input will have an action to clear the entered value.false
defaultValuestringInitial value of the input, only when it is uncontrolled.-
disabledbooleanIf true, the component will be disabled.false
errorstringIf it is a defined value and also a truthy string, the component will change its appearance, showing the error below the input component. If the defined value is an empty string, it will reserve a space below the component for a future error, but it would not change its look. In case of being undefined or null, both the appearance and the space for the error message would not be modified.-
helperTextstringHelper text to be placed above the input.-
labelstringText to be placed above the input. Under the hood, this prop also serves as an accessible label for the list of suggestions.-
margin'xxsmall' | 'xsmall' | 'small' | 'medium' | 'large' | 'xlarge' | 'xxlarge' | MarginSize of the margin to be applied to the component. You can pass an object with 'top', 'bottom', 'left' and 'right' properties in order to specify different margin sizes.-
maxLengthnumberSpecifies the maximum length allowed by the input. This will be checked both when the input element loses the focus and while typing within it. If the string entered does not comply the maximum length, the onBlur and onChange functions will be called with the current value and an internal error informing that the value length does not comply the specified range. If a valid length is reached, the error parameter of both events will not be defined.-
minLengthnumberSpecifies the minimum length allowed by the input. This will be checked both when the input element loses the focus and while typing within it. If the string entered does not comply the minimum length, the onBlur and onChange functions will be called with the current value and an internal error informing that the value length does not comply the specified range. If a valid length is reached, the error parameter of both events will not be defined.-
namestringName attribute of the input element.-
onBlur(val: { value: string; error?: string }) => voidThis function will be called when the input element loses the focus. An object including the input value and the error (if the value entered is not valid) will be passed to this function. If there is no error, error will not be defined.-
onChange(val: { value: string; error?: string }) => voidThis function will be called when the user types within the input element of the component. An object including the current value and the error (if the value entered is not valid) will be passed to this function. If there is no error, error will not be defined.-
optionalbooleanIf true, the input will be optional, showing '(Optional)' next to the label. Otherwise, the field will be considered required and an error will be passed as a parameter to the onBlur and onChange functions when it has not been filled.false
patternstringRegular expression that defines the valid format allowed by the input. This will be checked both when the input element loses the focus and while typing within it. If the string entered does not match the pattern, the onBlur and onChange functions will be called with the current value and an internal error informing that this value does not match the pattern. If the pattern is met, the error parameter of both events will not be defined.-
placeholderstringText to be put as placeholder of the input.-
prefixstringPrefix to be placed before the input value.-
readOnlybooleanIf true, the component will not be mutable, meaning the user can not edit the control. In addition, the clear action will not be displayed even if the flag is set to true and the custom action will not execute its onClick event.false
refReact.Ref<HTMLDivElement>Reference to the component.-
size'small' | 'medium' | 'large' | 'fillParent'Size of the component.'medium'
suffixstringSuffix to be placed after the input value.-
suggestionsstring[] | ((value: string) => Promise <string[]>)These are the options to be displayed as suggestions. It can be either an array or a function:
  • Array: List of options that will be filtered by the user's input.
  • Function: This function will be called when the user changes the value. It will receive the new value as a parameter and should return a promise that resolves to an array with the filtered options.
-
tabIndexnumberValue of the tabindex attribute.0
valuestringValue of the input. If undefined, the component will be uncontrolled and the value will be managed internally by the component.-

Examples

Controlled

() => {
  const [value, setValue] = useState("");
  const onChange = ({ value }) => {
    setValue(value);
  };
  const onBlur = ({ value }) => {
    setValue(value);
  };
  
  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcTextInput
        label="Enter your name"
        value={value}
        onChange={onChange}
        onBlur={onBlur}
      />
    </DxcInset>
  );
}

Uncontrolled

() => {
  const inputRef = useRef();

  const handleSubmit = () => {
    const input = inputRef.current.getElementsByTagName("input")[0];
    console.log(input.value);
  };

  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcFlex direction="column" gap="var(--spacing-gap-xl)" alignItems="flex-start">
        <DxcTextInput
          label="Enter your surname"
          defaultValue="Harris"
          ref={inputRef}
        />
        <DxcButton label="Submit" onClick={handleSubmit} />
      </DxcFlex>
    </DxcInset>
  );
}

Action

() => {
  const [value, setValue] = useState("");
  const onChange = ({ value }) => {
    setValue(value);
  };
  const actionIcon = {
    icon: "Content_Copy",
    onClick: () => {
      navigator.clipboard
        .writeText(value)
        .then(() => {
          alert("Code copied!");
        })
        .catch(() => {
          alert("Failed attempt to copy the text.");
        });
    },
    title: "Copy the text",
  };

  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcTextInput 
        action={actionIcon}
        clearable
        label="Enter your name"
        onChange={onChange}
        value={value}
      />
    </DxcInset>
  );
}

Autosuggest

() => {
  const countries = ["Afghanistan", "Albania", "Algeria", "Andorra"];
  const [value, setValue] = useState("");
  const onChange = ({ value }) => {
    setValue(value);
  };
  const onBlur = ({ value }) => {
    setValue(value);
  };

  const callbackFunc = (newValue) => {
    const result = new Promise((resolve) =>
      setTimeout(() => {
        resolve(
          newValue
            ? countries.filter((option) =>
                option.toUpperCase().includes(newValue.toUpperCase())
              )
            : countries
        );
      }, 1500)
    );
    return result;
  };
  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcTextInput
        label="Enter your country"
        value={value}
        onChange={onChange}
        suggestions={callbackFunc}
        onBlur={onBlur}
      />
    </DxcInset>
  );
}

Error handling

() => {
  const [value, setValue] = useState("");
  const [errorMessage, setErrorMessage] = useState();
  const onChange = ({ value, error }) => {
    setValue(value);
    setErrorMessage(error == undefined ? "" : "Error onChange: invalid email");
  };
  const onBlur = ({ value, error }) => {
    setValue(value);
    setErrorMessage(error == undefined ? "" : "Error onBlur: invalid email");
  };

  const validEmail = new RegExp(
    "^[a-zA-Z0-9._:$!%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]$"
  );

  return (
    <DxcInset space="var(--spacing-padding-xl)">
      <DxcTextInput
        label="Enter your email"
        onChange={onChange}
        onBlur={onBlur}
        error={errorMessage}
        pattern={validEmail}
      />
    </DxcInset>
  );
}