Amir hossein Majidi
Amir hossein Majidi

Reputation: 1

How to reset radio buttons in formik using useformik resetForm or handleReset functions?

I have a form which i want my inputs be cleared after a success submit,useFormik handleReset or useformik.resetForm() works fine on the text type inputs,but the radio buttons are still remain checked,is there any way i can solve this problem without using state for each radio? Here is hte code:

import {useFormik} from 'formik'
import * as Yup from 'yup'
import logo from "../images/logoRedBig.jpg";
import axios from 'axios'
import Modal from '../components/CustomModal'
import { useState } from 'react';

function Bform() {
    const [successOpen,setSuccessOpen] = useState(false)
    const [errorOpen,setErrorOpen] = useState(false)
    const [check,setCheck] = useState(false)
    const submitHandler = async (values) => {
            formik.resetForm()
    };
    const formik = useFormik({
        initialValues:{
            firstName: '',
            lastName: '',
            city:'',
            age:'',
            phone:'',
            occupation:'',
            yearsOfService:'',
            cityOfService:'',
            desiredCity:'',
            currentCompany:'',
            avgCurrSalary:'',
            type:'',
            aboutYou:''
        },
        onSubmit: (values) => submitHandler(values),
        validationSchema: Yup.object({
            firstName: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید").required("* نام الزامیست الزامیست"),
            lastName: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید").required("* نام خانوادگی الزامیست"),
            occupation: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید").required("* شغل فعلی الزامیست"),
            city: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید"),
            cityOfService: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید"),
            desiredCity: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید").required("* شهر مد نظر الزامیست"),
            currentCompany: Yup.string().matches(/[آ-ی]/, "*  فارسی وارد کنید"),
            aboutYou: Yup.string().matches(/^[ آابپتثجچحخدذرزژسشصضطظعغفقکگلمنوهیئ?u06F0-\u06F0-9\s]+$/, "*  فارسی وارد کنید"),
            yearsOfService: Yup.string().matches(/([u06F0-\u06F1-9])/, "*  عدد وارد کنید"),
            age: Yup.string().matches(/([0-9])/,"الگو اشتباه است").required("* سن الزامیست"),
            avgCurrSalary: Yup.string().matches(/([1-9])/,"  عدد وارد کنید"),
            phone: Yup.string().matches(/^([u06F0-\u06F0-9\s\-\+\(\)]*)$/,"* الگو اشتباه است")
            .required("* شماره همراه الزامیست").min(10,"* حداقل باید 10 رقم وارد شود"),
        })
    })
    


  return (
    <form onSubmit={formik.handleSubmit}>
        {successOpen ? <Modal isOpen={successOpen} onClose={()=>setSuccessOpen(!successOpen)}>
            <h2 className='font-semibold text-green-600'> درخواست همکاری شما با موفقیت ثبت شد</h2>
        </Modal> : null}
        {errorOpen ? <Modal isOpen={errorOpen} onClose={()=>{setErrorOpen(!errorOpen)}}>
            <h2 className='font-semibold text-red-600'> !متاسفانه ثبت اطلاعات شما با مشکل مواجه شد</h2>
        </Modal> : null}
        <div className='grid  text-lg font-bold
                        lg:grid-flow-col lg:py-2
                        xl:flex xl:justify-around xl:gap-5 '>
            <div className='grid gap-5
                            lg:col-span-1 lg:pl-5 lg:max-4xl:border-l lg:max-4xl:border-gray-500 xl:max-4xl:font-normal
                            xl:w-full'>
                <h1 className="text-lg font-extrabold">
                    فرم دریافت نمایندگی
                </h1>
                <div className='flex flex-col items-center font-bold
                                md:flex md:flex-col md:gap-1 md:items-center xl:max-4xl:font-normal'>
                    <label>
                        نام:
                    </label>
                    <input 
                        className='block rounded-md py-2 w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='firstName'
                        id='firstName'
                        placeholder='نام '
                        {...formik.getFieldProps('firstName')}
                    />
                    {formik.touched.firstName ?(formik.errors.firstName ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.firstName}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        نام خانوادگی:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1  ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='lastName'
                        id='lastName'
                        placeholder='نام خانوادگی'
                        {...formik.getFieldProps('lastName')}
                    />
                    {formik.touched.lastName ?(formik.errors.lastName ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.lastName}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        شهر محل سکونت:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='city'
                        id='city'
                        placeholder='شهر محل سکونت'
                        {...formik.getFieldProps('city')}
                    />
                    {formik.touched.city ?(formik.errors.city ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.city}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        سن:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='age'
                        id='age'
                        placeholder='سن'
                        {...formik.getFieldProps('age')}
                    />
                    {formik.touched.age ?(formik.errors.age ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.age}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        تلفن همراه:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='phone'
                        id='phone'
                        placeholder='09xxxxxxxxx'
                        {...formik.getFieldProps('phone')}
                    />
                    {formik.touched.phone ?(formik.errors.phone ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.phone}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        شغل فعلی:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='occupation'
                        id='occupation'
                        placeholder='شغل فعلی  '
                        {...formik.getFieldProps('occupation')}
                    />
                    {formik.touched.occupation ?(formik.errors.occupation ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.occupation}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        سابقه فعالیت:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='yearsOfService'
                        id='yearsOfService'
                        placeholder='سابقه فعالیت  '
                        {...formik.getFieldProps('yearsOfService')}
                    />
                    {formik.touched.yearsOfService ?(formik.errors.yearsOfService ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.yearsOfService}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        شهر محل فعالیت:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full md:text-center
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='cityOfService'
                        id='cityOfService'
                        placeholder='شهر محل فعالیت  '
                        {...formik.getFieldProps('cityOfService')}
                    />
                    {formik.touched.cityOfService ?(formik.errors.cityOfService ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.cityOfService}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        شهر مد نظر جهت اخذ نمایندگی:
                    </label>
                    {formik.touched.city ?(formik.errors.city ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.city}</p>
                                                              </div> : null) : null}
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                    md:w-full md:text-center
                                    xl:w-8/12
                                    3xl:w-6/12'
                        type='text'
                        name='desiredCity'
                        id='desiredCity'
                        placeholder='شهر مد نظر جهت اخذ نمایندگی'
                        {...formik.getFieldProps('desiredCity')}
                    />
                    {formik.touched.desiredCity ?(formik.errors.desiredCity ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.desiredCity}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        نام مجموعه فعلی:
                    </label>
                    <input 
                    className='block rounded-md w-full ring-1 py-2  ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                 md:w-full md:text-center
                                 xl:w-8/12
                                 3xl:w-6/12'
                        type='text'
                        name='currentCompany'
                        id='currentCompany'
                        placeholder='مجموعه فعلی'
                        {...formik.getFieldProps('currentCompany')}
                    />
                    {formik.touched.currentCompany ?(formik.errors.currentCompany ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.currentCompany}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        متوسط درآمد ماهیانه فعلی:
                    </label>
                    <input 
                        className='block rounded-md py-2  w-full ring-1   ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                                     md:w-full 
                                     xl:w-8/12
                                     3xl:w-6/12'
                        type='text'
                        name='avgCurrSalary'
                        id='avgCurrSalary'
                        placeholder='متوسط درآمد ماهیانه فعلی'
                        {...formik.getFieldProps('avgCurrSalary')}
                    />
                    {formik.touched.avgCurrSalary ?(formik.errors.avgCurrSalary ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.avgCurrSalary}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label className='text-sm font-bold'>
                        کدامیک از موارد زیر را انتخاب می کنید؟
                    </label>
                    <div className='flex flex-col ga  items-center
                                    lg:max-3xl:items-start'>
                        <div className='flex gap-1 '>
                            <label>
                                نمایندگی فروش
                            </label>
                            <input
                                type='radio'
                                name='type'
                                value="نمایندگی فروش"
                                onChange={formik.getFieldProps("type").onChange}
                            />
                        </div>
                        <div className='flex gap-1 '>
                            <label>
                                عاملیت فروش 
                            </label>
                            <input
                                type='radio'
                                name='type'
                                value="عاملیت فروش"
                                onChange={formik.getFieldProps("type").onChange}
                            />
                        </div>
                        <div className='flex gap-1'>
                            <label>
                               همکاری
                            </label>
                            <input
                                type='radio'
                                name='type'
                                value="همکاری"
                                onChange={formik.getFieldProps("type").onChange}
                            />
                        </div>
                        <div className='flex gap-1 '>
                            <label>
                                سرمایه گذاری
                            </label>
                            <input
                                type='radio'
                                name='type'
                                value="سرمایه گذاری"
                                checked={formik.type ==="سرمایه گذاری"}
                                onChange={formik.getFieldProps("type").onChange}
                            />
                        </div>
                    </div>

                </div>
                <div className='flex flex-col items-center
                                md:flex md:flex-col md:gap-1 md:items-center'>
                    <label>
                        توضیحات بیشتر:
                    </label>
                    <textarea 
                        className='block rounded-md p-5 w-full ring-1 placeholder:py-2 focus:text-sm  ring-gray-500 placeholder:text-gray-400 bg-gray-100 border-0  text-center text-black focus:outline-gray-500
                        md:w-full md:text-center md:p-10
                        lg:max-3xl:p-10 
                        xl:w-8/12
                        3xl:w-6/12'
                        name='aboutYou'
                        id='aboutYou'
                        placeholder='ما را با خود بیشتر آشنا کنید'
                        {...formik.getFieldProps('aboutYou')}
                    />
                    {formik.touched.aboutYou ?(formik.errors.aboutYou ? <div>
                                                                    <p className='text-red-500 lg:max-3xl:text-sm'>{formik.errors.aboutYou}</p>
                                                              </div> : null) : null}
                </div>
                <div className='flex items-center justify-center py-3 
                        lg:max-3xl:pb-10'>
                    <button 
                        className='w-full rounded-md p-2 text-center focus:shadow-md focus:outline-none text-white bg-red-700 self-center
                                md:w-4/12 
                                xl:max-2xl:w-2/12
                                3xl:w-1/12
                                '
                        title='ثبت'
                        type="submit"
                        >
                        ثبت
                    </button>
                </div>
            </div>
            <div className='lg:col-span-2 lg:max-3xl:px-1'>
                <img
                    src={logo}
                    alt="لوگوی رادین"
                    className='w-0 h-0
                            lg:w-full lg:h-full 
                            xl:w-full xl:h-full '
                />
            </div>
        </div>
    </form>
  )
}


export default Bform

i tried using handleReset() and resetForm() but it didn't work. i managed to solve it with using 4 states for each radio,but idon't like the idea of it and i want to find a better solution,because i have another form with more radio buttons.

Upvotes: 0

Views: 127

Answers (1)

Sunamin34
Sunamin34

Reputation: 388

For the radio inputs that you want to reset, try assiging the value of the formik form to the checked attributes and see if that fixes your issue. Example with the radio input for the attribute "type"

...
<input
  type='radio'
  name='type'
  value="عاملیت فروش"
  checked={formik.values.type === "عاملیت فروش" ? true : false}
  onChange={formik.getFieldProps("type").onChange}
/>
...

Right now I suspect the actual value of the "type" attribute to be empty, meaning an empty string, but the radio input to still be checked for no obvious reason.

Upvotes: 0

Related Questions