Published on

How to use Chakra UI Radio Component with React Hook Form

Authors

Building forms is one of the tedious thing in developing web application. We have to think about lot of things like handling data, validations, etc but React Hook Form makes it easy for us to do it.

In this article, let's see how to handle Chakra UI 's radio component with React Hook Form. But it's pretty much same for all the custom components.

Let's install the dependencies first.

npm install @chakra-ui/core@0.8.0 react-hook-form

And we'll be using Controller component from react-hook-form to handle our custom components.

Here's an example of it:

import { RadioGroup, Radio } from '@chakra-ui/core'
import { useForm, Controller } from "react-hook-form";
const RadioFormDemo = () => {
    const { register, handleSubmit, errors, reset, control } = useForm();
    const onSubmit =  data => {
        console.log(data)
    }
    return (
        <form onSubmit={handleSubmit(onSubmit)} >
        <FormControl>
            <FormLabel>Gender</FormLabel>
            <Controller
                as={
                    <RadioGroup ref={register()} name="gender" isInline spacing={4} defaultValue="MALE">
                        <Radio value="MALE"> Male </Radio>
                        <Radio value="FEMALE">Female</Radio>
                    </RadioGroup>
                }
                name="gender"
                control={control}
            />
        </FormControl>
        </form>
    )
}
export default RadioFormDemo;

Hope that helps :)

References