Fluent UI React v9 with Formik and Yup
Tags: fluentui, webdev, react, tutorial
Published: 2022-07-15 16:23:27

This post was inspired by the documentation examples from the [Formik](https://formik.org/docs/examples/with-material-ui) documentation.

This tutorial assumes that you have some previous experience working with [Formik](https://formik.org/) and [Yup](https://github.com/jquense/yup). If you are, then this becomes an exercise of mapping formik props to corresponding Fluent UI React Components. 

This tutorial will cover high-level usage of Formik, but it's recommended you go read through the documentation to learn more.

## 1. Install the necessary dependencies
For this example, it's recommended that you install the following npm dependencies:
- `npm install formik` handling form data
- `npm install yup` for value parsing and validation
- `npm install @fluentui/react-components` - for Form components
- `npm install @fluentui/react-icons` - for icons

## 2. Build out your Form
For this example we're building the following login experience and will break down composing the UI and adding in the Formik and Yup validation:
![Screenshot of a Login experience with Fluent UI React Components](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4ri2und078n4tn2qvsr.png)

### Compose the form layout with CSS-in-JS
We start off with the high-level layout of the form leveraging [Griffel](https://griffel.js.org), the CSS-in-JS engine that comes with Fluent UI React. 

Let's start off using CSS Flexbox to lay everything out in a vertical stack with a maximum width of 480px:
```
const useStyles = makeStyles({
  form: {
    display: "flex",
    flexDirection: "column",
    maxWidth: "480px"
  }
});
```
Apply it to our UI using the `className` prop on the `form`.

```
export default function App() {
  const c = useStyles();
  return (
    <FluentProvider theme={webLightTheme}>
        <form className={c.form}>
        </form>
    </FluentProvider>
  );
}
```

### Add in Fluent UI React Components
We'll be using the [Input](https://react.fluentui.dev/?path=/docs/components-input--default), [Label](https://react.fluentui.dev/?path=/docs/components-label--default), and [Button](https://react.fluentui.dev/?path=/docs/components-button-button--default) components.

Also I created a small little `ErrorText` component to help display the error messages after validation.

```
export default function App() {
  const c = useStyles();
  const inputId = useId("input");
  const passId = useId("pass");
  return (
    <FluentProvider theme={webLightTheme}>
        <form className={c.form}>
          <Label htmlFor={inputId} required>
          Email
          </Label>
          <Input
            id={inputId}
            name="email"
            placeholder="hello@fluentui.dev"
          />
          <ErrorText />
          <Label htmlFor={passId} required>
          Password
          </Label>
          <Input
            id={passId}
            name="password"
            type="password
           />
          <ErrorText />
          <Button appearance="primary" type="submit">
          Login
          </Button>
        </form>
    </FluentProvider>
  );
}
```

## 3. Add in Formik and Yup
Finally add in Formik for handling the form data and Yup for creating your form parsing and validation.

### Declare your Yup validation
Let's set up simple validation for the email and password entries.
```
const validationSchema = yup.object({
  email: yup
    .string()
    .email("Enter a valid email")
    .required("Email is required"),
  password: yup
    .string()
    .min(8, "Password should be of minimum 8 characters length")
    .required("Password is required")
});
```

### Declare Formik initial values, assign the validation, and define your submit action
For this example, `onSubmit` will just `alert` the values of the form, but you can imagine this could call any backend service.

```
const formik = useFormik({
  initialValues: {
    email: "",
    password: ""
  },
  validationSchema: validationSchema,
  onSubmit: (values) => {
    alert(JSON.stringify(values, null, 2));
  }
});
```

### Map Formik props to Fluent UI React Components
This one is pretty straightforward in that you simply match the up the Formik prop with Fluent UI React Component prop.

```
<form onSubmit={formik.handleSubmit}>
  <Input 
    value={formik.values.email}
    onBlur={formik.handleBlur}
    onChange={formik.handleChange}
  />
  ...
  <Button appearance="primary" type="submit">Login</Button>
</form>
```
You should get the idea here.

As always, here's the complete CodesandBox:
{% embed https://codesandbox.io/embed/fluentui-formik-wzkupp?fontsize=14&hidenavigation=1&theme=dark %}

Finally, be sure to check out the `ErrorText` Component. It's just a React Functional Component with some CSS-in-JS, Design Tokens, Fluent UI React Icons, and HTML.

Let us know what other code examples you want to see and feel free to reach out to the team!

- GitHub: https://github.com/microsoft/fluentui
- Docs: https://react.fluentui.dev
- Twitter: https://twitter.com/fluentui

Thanks!