How to make use of Radio Group with useFormik Hook

Viewed 2143

I am trying to get useFormik to validate radio groups, but it seems not to work, here is a brief example of what I am doing, whenever I submit the form after checking any of the radio input, formik throws validation error, ({currState:"you must choose property state"}), even though I choose an option. I realized getFieldProps attaches value field to the radio, so i tried using defaultValue then react throws an error about choosing one of controlled and uncontrolled components.

     import { useFormik } from "formik"
     export function ListProperty(){
     const { handleSubmit, getFieldProps, touched, errors } = useFormik(
             {
           initialValues: {
            currState:"",
          },
      validationSchema:Yup.object().shape({
         currState:Yup.string().required("you must choose property state")
     }),
     return (
        <form onSubmit={handleSubmit} >

         <div className="form-group inline">
            <div className="form-control">
              <input type="radio" 
              name="currState"  
              {...getFieldProps("currState")} 
              value="serviced" 
              />
              <label>serviced</label>
            </div>

            <div className="form-control">
              <input 
              type="radio" 
              value="furnished" 
              name="currState"  
              {...getFieldProps("currState")} 
              />
              <label>furnished</label>
            </div>

            <div className="form-control">
              <input
                type="radio"
                value="newlybuilt"
               name="currState"  
              {...getFieldProps("currState")} 
              />
              <label>newly built</label>
            </div>

          </div>
           <button type="submit">submit </button>
           </form>
     )
   }
2 Answers

You need to map onChange like below.

<input 
  type="radio" 
  value="furnished" 
  name="currState"  
  onChange={getFieldProps("currState").onChange} 
/>

I gave up on the implementation with getFieldProps and did it simpler, like this:

import { useFormik } from 'formik'

export default function Component() {

  const formik = useFormik({
    initialValues: { 
      radioButtonValue: ''
    },
    onSubmit: values => console.log(values)
  })

  const handleRadioButtons = e => formik.values.radioButtonValue = e.target.value

  return (
   <form onSubmit={formik.handleSubmit}>
     <input 
       type="radio" 
       id="one"
       name="group" 
       value="One" 
       onChange={e => handleRadioButtons(e)}
       required
     />
     <label htmlFor="one">One</label>
     <br />

     <input 
       type="radio" 
       id="two"
       name="group" 
       value="Two" 
       onChange={e => handleRadioButtons(e)}
     />
     <label htmlFor="two">Two</label>

     <button type="submit">Submit</button>
   </form>
  )
}
Related