Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add Radio Button in Formik Validations Reactjs?

Tags:

reactjs

I am using Formik for Validating my Registration form I want to add validate gender via radio button how can I do that. I am not able to add radio button.

This is what I have done:-

 const SignupSchema = Yup.object().shape({
        email: Yup.string()
          .email('Invalid email')
          .required('Required'),
        password: Yup.string()
          .min(4, 'Password Must be four characters long!')
          .max(20, 'Too Long!')
          .required('Required'),

      });
    class Register extends Component {
        render() {
            return (
                   <Formik
                     initialValues={{
                        email: '',
                        password:'',
                        gender:'',

                     }}
                     validationSchema={SignupSchema}
                     onSubmit={values => {
                       console.log(values);
                     }}
                   >
                     {({ errors, touched }) => (
                       <Form>

                         <Field style={customStyles.textfield} placeholder="Email" name="email" type="email" />
                         {errors.email && touched.email ? <div}>{errors.email}</div> : null}

                         <Field placeholder="Enter Password" name="password" type="password" />
                         {errors.password && touched.password ? <div >{errors.password}</div> : null}


                         <button type="submit">Submit</button>
                       </Form>
                     )}
                   </Formik>
             </div>
            )
        }
    }
like image 232
Chandrapratap Avatar asked Oct 28 '25 17:10

Chandrapratap


2 Answers

change gender initialValues as male

        <Field
          name="gender"
          render={({ field }) => (
            <>
              <div className="radio-item">
                <input
                  {...field}
                  id="male"
                  value="male"
                  checked={field.value === 'male'}
                  name="type"
                  type="radio"
                />
                <label htmlFor="male">Male</label>
              </div>

              <div className="radio-item">
                <input
                  {...field}
                  id="female"
                  value="female"
                  name="type"
                  checked={field.value === 'female'}
                  type="radio"
                />
                <label htmlFor="female">Female</label>
              </div>
            </>
          )}
        />
like image 119
demkovych Avatar answered Oct 31 '25 08:10

demkovych


This solution gives you the chance to have more than 2 options.

Let say you have a file called Main.js and you want to put a radio button input in it. First, provide a list of options for your radio button in the Main.js

const radioOptions = [
    { key: 'Option 1', value: 'value 1' },
    { key: 'Option 2', value: 'value 2' },
    { key: 'Option 3', value: 'value 3' }
  ];

Next, create a RadioButton.js file with below code

import React from 'react';
import { Field } from 'formik';

const RadioButton = (props) => {
  const { label, name, options, ...rest } = props;
  return (
    <div>
      <label htmlFor={name}>{label}</label>
      <Field name={name} {...rest} >
        {
          ({ field }) => {
            return options.map(option => {
              return (
                <React.Fragment key={option.key}>
                  <input
                    type='radio'
                    id={option.id}
                    {...field}
                    value={option.value}
                    checked={field.value === option.value}
                  />
                  <label htmlFor={option.id}>{option.key}</label>

                </React.Fragment>
              );
            })
          }
        }
      </Field>
    </div>
  );
};

export default RadioButton;

Then put the reusable RadioButton Component in the Main.js wherever you want the radio button input to render.

The result UI will be 3 radio buttons with values "value 1", "value 2" and "value 3".

You can check out this awesome youtube series to know more.

like image 40
HeLin Avatar answered Oct 31 '25 06:10

HeLin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!