Blog>
Snippets

Integrating TanStack Form with React UI Components

Show how to integrate TanStack Form with React functional components for UI rendering, focusing on custom input and error display components.
import { useForm, useField } from 'tanstack-form-react';
import { TextField, Button, Alert } from '@material-ui/core';
This code imports the necessary hooks from TanStack Form and components from Material-UI that will be used for the UI.
const CustomTextInput = ({ label, ...props }) => {
  const {
    getInputProps,
    meta: { error, isTouched }
  } = useField(props);
  
  return (
    <>
      <TextField {...getInputProps({ refKey: 'inputRef' })} label={label} error={!!error && isTouched} helperText={isTouched ? error : ''} />
    </>
  );
};
Defines a custom text input component using a Material-UI TextField. It utilizes useField from TanStack Form to handle form state and validation. If there's an error and the field was touched, it shows the error message.
const FormComponent = () => {
  const {
    formContext: { submit },
    Form,
  } = useForm({
    onSubmit: async (values) => alert(JSON.stringify(values)),
  });
  
  return (
    <Form>
      <CustomTextInput name='username' label='Username' />
      <Button type='submit' onClick={() => submit()}>
        Submit
      </Button>
    </Form>
  );
};
Sets up a form using the TForm component from TanStack Form. It includes the CustomTextInput for user input and uses a Material-UI Button for submission. Upon submitting, it shows an alert with form values.
export default FormComponent;
Exports the FormComponent to be used elsewhere in the application.