Advanced Formik integration

Chakra UI can be coupled smoothly with Formik, by the end of the example up ahead, you will be proficient at Chakra & Formik.

In the ImageRadio component, we will utilize the useRadio hook from Chakra UI to get the necessary props and the isChecked boolean. isChecked will be used for validation in Formik's useField hook.

To finalize, we will need to render our content and pass getInputProps and getCheckedProps from Chakra UI.

import { Box, Button } from "@chakra-ui/react";
import { Formik, FormikProps } from "formik";

import Input from "./input";
import RadioGroup from "./radio-group";
import ImageRadio from "./image-radio";

const AVATARS = [
  { name: "Kat", image: "https://randomuser.me/api/portraits/women/44.jpg" },
  { name: "Kevin", image: "https://randomuser.me/api/portraits/men/86.jpg" },
  { name: "Andy", image: "https://randomuser.me/api/portraits/men/29.jpg" },
  { name: "Jess", image: "https://randomuser.me/api/portraits/women/95.jpg" }
];

type Values = {
  email: string;
  avatar: string;
};

export default function App() {
  return (
    <Box p={24}>
      <Formik
        initialValues={{ email: "", avatar: AVATARS[0].name }}
        onSubmit={console.log}
      >
        {(props: FormikProps<Values>) => (
          <form onSubmit={props.handleSubmit}>
            <Input name="email" />
            <RadioGroup name="avatar" py={2} display="flex" gridColumnGap={2}>
              {AVATARS.map(({ name, image }) => {
                console.log("App line 32 ~ name: ", name)
                return (
                <ImageRadio key={image} image={image} value={name} />
              )})}
            </RadioGroup>
            <Button type="submit">Submit</Button>
          </form>
        )}
      </Formik>
    </Box>
  );
}

In the example above, there are 2 more components:

  • Radio Group - which renders multiple radio buttons
  • Input - where we will enter our value of choice

Upon submitting the form, in the CodeSandbox console, you should see the result of which radio you've selected but also the value of the input.

If you have any questions, or need help around an advanced usage, don't hesitate to reach out in our Discord server.

Proudly made inNigeria by Segun Adebayo

Deployed by â–² Vercel