Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

withFormik(): How to use handleChange

Tags:

reactjs

formik

Current platform: NodeJS (minimal), client-side React w/Redux, Formik, Yup.

Given the following example code (not including the entire React Component code since it's irrelevant to the question):

class RegisterPage extends React.Component {
    constructor(props) {
        super(props);
    }

    // (...)

    render () {
        <Form>
            <Field name="email" type="email" />
            <Field name="password" type="password" />
            <Field 
                name="myCheckbox" 
                type="checkbox"
                checked={this.props.values.myCheckbox}
                onChange={  ??????????  } />
        </Form>
    }
}

const handleFormSubmission = (values, { resetForm, setErrors, setSubmitting }) => {
    console.log(values);
};

const handleFormChange = (event) => {
    event.persist();
    console.log('changed');
};

const MyFormik = withFormik({
    mapPropsToValues ({ email, password, myCheckbox }) {
        return {
            email: email || '',
            password: password || '',
            myCheckbox: myCheckbox || false
       }
    },
    validationSchema: (...Yup schema here...),
    handleSubmit (values, bag) { return handleFormSubmission(values, bag); }
})(RegisterPage);

export default connect()(MyFormik);

...how can I use the handleChange method? I need to persist the original one (the one from Formik) while adding code that handles that checkbox change. There's some component behavior that depends on the checked value of that checkbox.

Please notice that I'm not passing the onChange prop to email or password, since there is no extra behavior to code for on those. The checkbox is the one that will have special behavior.

like image 861
Arnie Avatar asked Jul 03 '18 16:07

Arnie


2 Answers

Just in case if you want to handle checkbox

onChange={(e, event) => {
   handleChange({ ...event, target: { name: 'isDeleted', value: e } })
}}
like image 145
Muhammad Ahmad Avatar answered Dec 18 '22 17:12

Muhammad Ahmad


You can declare a handler for the checkbox, and use it! Using the native handler of Formkit, and your custom handler.

class RegisterPage extends React.Component {
   constructor(props) {
      super(props);
   }
   // (...)
   handleCheckBox: (e) => {
       // do whatever you want to the value
   }
   render () {
       <Form>
           <Field name="email" type="email" />
           <Field name="password" type="password" />
           <Field 
               name="myCheckbox" 
               type="checkbox"
               checked={this.props.values.myCheckbox}
               onChange={(e) => {this.props.handleChange(e); this.handleCheckBox(e)}} />
       </Form>
   }
}
like image 21
reisdev Avatar answered Dec 18 '22 17:12

reisdev