Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Checkbox and Radio Buttons with Formik, Yup, Ui Kitten in React Native

I am using Formik and yup for forms in my app. I am not able to implement checkbox with Formik, implemented this solution but its not working with me. Below is the code I have tried so far. After implementing this solution when i click on checkbox the form become invalid and submit button does not call handleSubmit method. I also tried using React Native Elements instead of UI Kitten but result was the same.

const validationSchema = Yup.object().shape({

  service_charge_status: Yup.boolean(),//.oneOf([true], 'Please check the agreement'),
  documents_status: Yup.boolean(), //.oneOf([true], 'Please check the agreement'),
  security_number: Yup.string()
    .label('Security Number *')
    .required('Security Number is required'),
  note: Yup.string().label('Note')


    })
    handleSubmit = (values: any) => {
    console.log('AD Values', values);
  }

  render() {
    return (
      <Formik
        initialValues={{
          // id: '',
          service_charge_status: false,
          documents_status: false,
          security_number: '',
          note: '',
          security_personel_number: ''
        }}
        onSubmit={values => { this.handleSubmit(values) }}
        validationSchema={validationSchema}
      >
        {({ handleChange,
          values,
          handleSubmit,
          errors,
          isValid,
          isSubmitting,
          touched,
          handleBlur,
          setFieldValue }
        ) => (<ScrollView>
          <Header
            noBackButton={true}
            navigation={this.props.navigation}
            title="Approve Request"
          />
          <Layout style={{ padding: 20 }}>
            <View style={{ marginVertical: 5 }}>
              <Text category="p1" style={{ marginVertical: 5 }}>
                Requester Type
            </Text>
              <View style={{ flexDirection: 'row' }}>
                <RadioGroup
                  selectedIndex={this.state.requestTypeIndex}
                  onChange={(index) => this.setState({ requestTypeIndex: index })}                >
                  <Radio
                    text="New Issue"
                    textStyle={styles.labelColor}
                    // checked={values.is_new_issue}
                    status="warning"
                  />
                  <Radio
                    text="Replacement"
                    textStyle={styles.labelColor}
                    // checked={values.is_replacement}
                    // onChange={handleChange('is_replacement')}
                    status="warning"
                  />
                </RadioGroup>
              </View>
            </View>
            <View style={{ marginVertical: 5 }}>
              <Text category="p1" style={{ marginVertical: 5 }}>
                Check List
            </Text>
              <Layout style={{ marginVertical: 6 }}>
                <CheckBox

                  text="Service Charges"
                  textStyle={styles.labelColor}
                  status="warning"
                  checked={values.service_charge_status}
                  onChange={(val) => setFieldValue('service_charge_status', !values.service_charge_status)}

                />
              </Layout>

              <Layout style={{ marginVertical: 6 }}>
                <CheckBox

                  text="Documents Verification"
                  textStyle={styles.labelColor}
                  status="warning"
                  checked={values.documents_status}
                  onChange={(val) => setFieldValue('documents_status', !values.documents_status)}
                />
              </Layout>
            </View>
            <View style={{ marginVertical: 5 }}>
              <Text category="p1" style={{ marginVertical: 5 }}>
                Security Personel Number *
            </Text>
              <Input
                placeholder="Enter Security personel number"
                size='small'
                multiline={true}
                status={touched.security_personel_number ? !errors.security_personel_number ? 'success' : 'danger' : 'warning'}
                caption={(touched.security_personel_number && errors.security_personel_number) ? errors.security_personel_number : ''}
                value={values.security_personel_number}
                onChangeText={handleChange('security_personel_number')}
              />
              <Text category="p1" style={{ marginVertical: 5 }}>
                Note *
            </Text>
              <Input
                placeholder="Enter Note"
                size='small'
                multiline={true}
                status={touched.note ? !errors.note ? 'success' : 'danger' : 'warning'}
                caption={(touched.note && errors.note) ? errors.note : ''}
                value={values.note}
                onChangeText={handleChange('note')}
              />
            </View>

            {this.state.formSpinner &&
              <View style={styles.centeredContentViewStyle}>
                <ActivityIndicator animating size="small" color="#fbaf3a" />
              </View>}

            {this.state.error ?
              <View style={styles.centeredContentViewStyle}>
                <Text style={styles.errorMessageStyle}>{this.state.error}</Text>
              </View> : null}

            <Layout
              style={{
                justifyContent: 'flex-end',
                flexDirection: 'row',
                marginVertical: 10,
              }}>
              <Button
                style={styles.cancelButton}
                onPress={() => this.props.navigation.goBack()}>
                Cancel
            </Button>

              <Button
                style={styles.submitButton}
              // type="submit"
              // disabled={!isValid || this.state.formSpinner}
              >
                {isValid + ' Submit'}
              </Button>
            </Layout>
          </Layout>
        </ScrollView>)}
      </Formik>
    );
  }
}

const styles = StyleSheet.create({
  submitButton: {
    borderColor: '#00c851',
    backgroundColor: '#00c851',
    marginStart: 5,
  },
  cancelButton: {
    borderColor: '#ff3547',
    backgroundColor: '#ff3547',
  },
  labelColor: {
    color: '#8F9BB3',
  },
  centeredContentViewStyle: {
    justifyContent: 'center',
    alignItems: "center",
    padding: 2,
    marginVertical: 5
  },
  errorMessageStyle: {
    color: 'red'
  }
});
like image 202
Imdad Ali Avatar asked Dec 16 '19 08:12

Imdad Ali


People also ask

How do I add a radio button in React Native?

To do so, go to RadioButton. js and modify the return block to the following: import {Pressable} from 'react-native'; //additional import. //code to change of 'return' block in RadioButton.

How do you use Formik and yup in React Native?

Build Form in React Native with Formik Now, we are going to create a basic form using the Formik component. Open your App. js file and import the formik package at the top part of the app file. Next, replace the following code with your existing code in the same file.


1 Answers

I'm using Formik with Chakra UI's Checkbox and ended up using the onChange event to solve this issue like so:

<Field name="terms">
  {({ field }) => (
    <Checkbox
      id="terms"
      name="terms"
      onChange={(e) => setFieldValue('terms', e.target.checked)}
    >
      <Text fontSize="sm" textAlign="left">
        I agree to the Terms and Conditions.
      </Text>
    </Checkbox>
  )}
</Field>

I believe something similar with work with UI Kitten.

This GitHub comment was really helpful for Yup validation.

like image 79
lightstrike Avatar answered Sep 28 '22 05:09

lightstrike