Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Formik Field onChange event handle

I am trying to handle onChange for Field component in React Formik, but it doesn't work. I also tried to handle it outside Formik component by:

handleChange(e) {
  console.log('changing');
}
<Field type="radio" name="players" value="1" onChange={e => this.handleChange(e)}/>

but I am getting the warning:

A component is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa).

For now my code looks like this:

<Formik
  onChange={() => {
    console.log('changing');
  }}
  onSubmit={(values) => {
    console.log('submitted');
  }}
>
{({ isSubmitting, handleChange }) => (
  <Form>
    <InputWrapper>
       <span>1</span>
       <Field type="radio" name="players" value="1" onChange={handleChange}/>
       <span>2</span>
       <Field type="radio" name="players" value="2" onChange={handleChange}/>
    </InputWrapper>
    <button type="submit" disabled={isSubmitting}>
       {isSubmitting ? 'Loading..' : 'Start'}
    </button>
  </Form>
)}
</Formik>

Any tips/ideas?

like image 749
Mindfuc Avatar asked Oct 18 '18 07:10

Mindfuc


People also ask

How do I get onChange event in Formik?

Solution 1: Attach callback on <form> Formik does not provide onChange prop, but <form> (or <Form> if using the wrapper version) does provide it.

How do you use handleChange in Formik?

Now we must write the handleChange method to update the state with user inputs: handleChange = ({ target }) => { const { formValues } = this. state; formValues[target.name] = target. value; this.

What is Formik dirty?

Returns true if values are not deeply equal from initial values, false otherwise. dirty is a readonly computed property and should not be mutated directly.

What is setSubmitting in Formik?

Proceed with running your submission handler (i.e. onSubmit or handleSubmit ) you call setSubmitting(false) in your handler to finish the cycle.

How to use handlechange() function in React component?

How to use handleChange () function in react component? An onChange event is triggered when values are entered in the input. This fires a function handleChange (), that is used to set a new state for the input. 1. Handling Single Input

How do I use formik with react context?

Method 2: Using Formik with React context The <Formik/> component exposes various other components that adds more abstraction and sensible defaults. For example, components like <Form/ >, <Field/>, and <ErrorMessage/> are ready to go right out of the box.

How to handle onchange event in formik?

Formik does not provide onChange prop, but <form> (or <Form> if using the wrapper version) does provide it. So, you can just define a handleOnChange callback function like this: {/* ... */} The callback is going to receive a synthetic DOM event, and you can access the input element triggering the change via event.target

What is the purpose of the onchange event in react?

The value is set to be in sync with fullName, which is already declared in the state. The onChange event is used to execute the handleChange function if there’s a change in the input field. The only new thing on the input field above is the addition of the name attribute.


3 Answers

One issue I have found with introducing the onBlur:handleBlur to your Formik Field is that it overrides the Formik Validation.

Use onKeyUp={handleChange}

This solved said problem

like image 55
Ray Yecko Avatar answered Oct 18 '22 02:10

Ray Yecko


You must to use the InputProps of Field like the following...

import { TextField } from 'formik-material-ui';

<Field
  type="radio" 
  name="players" 
  value="2"
  component={TextField} 
  InputProps={{ onBlur:handleBlur }}/>

To use the InputProps in the Field you need to use a component TextField from the formik-material-ui lib.

Another way is use the onKeyUp or onKeyDown, that functions work ok with Field and that functions are like onChange

<Field 
  type="radio" 
  name="players" 
  value="2" 
  onKeyUp =this.handleChange/>
like image 23
Iván López Acosta Avatar answered Oct 18 '22 01:10

Iván López Acosta


I found one trick which worked well for me, you can use "values" of formik and call a method passing the "values" as parameter and perform the action using new values.

const handleUserChange = (userId: number) => {
    //userId is the new selected userId
  };


 <Formik
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
        enableReinitialize
      >
        {({ isValid, isSubmitting, values }) => (
          <Form>
            <table className="table">
              <tbody>
                <tr>
                  <td>Users</td>
                  <td>
                    <Field name="userId" className="form-control" as="select">
                      <option value="">--select--</option>
                      {data.Users.map((user, index) => (
                        <option key={user.id} value={user.id}>{`User ${index + 1}`}</option>
                      ))}
                    </Field>
                  </td>
                </tr>
                {handleUserChange(values.userId)}
              </tbody>
            </table>

            <div className="row">
              <div className="col-sm-12">
                <SubmitButton label="Save" submitting={isSubmitting} disabled={!isValid || isSubmitting} />
              </div>
            </div>
          </Form>
        )}
      </Formik>
like image 2
Atif Avatar answered Oct 18 '22 03:10

Atif