Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Formik hidden field sending null value to server

Tags:

reactjs

formik

I am new to React i am using FormIK which is posting Form data fine unless i add a hidden field into it.

<Field type="hidden" className="form-control" name="hiddenField" /> 

When i post form it sends the Null value of hidden field Also i have provided initial values to Formik

<Formik initialValues={{
first_name:'',last_name:'',username:'',email:'',password:'',
password_confirmation:'',distributor:'',phone_number:'',address:'',country:'',
state:'',city:'',zip_code:'',hiddenField:''
}} >

Is there any thing missing ?

like image 380
Abdul Qadir R. Avatar asked Dec 20 '18 12:12

Abdul Qadir R.


People also ask

How do I access current value of a Formik field without submitting?

it is very simple just do console. log(formik. values) and you will get all the values without submitting it.

How do you reset field value in Formik?

If you want to reset the selected value after the form is submitted, you need to provide a controlled value for the Select component. The Formik Field component provides the value in the props object, so you can use it.

What is SetFieldValue?

The SetFieldValue method sets the value of a field. This method has the following syntax: integer = FieldObject.SetFieldValue(value = variable) This method has the following parameter: value.

What is Formik handleChange?

Formik has its own handleChange method that you can use to update the state with user inputs, there is no need to implement your own handleChange method. The handleChange method updates the form values based on the input's name attribute that was changed.


2 Answers

I just used ran into this issue as well. My work around was to just add an initial value, and not even use a hidden field. The result was, in onSubmit(), the values object contained my hidden field key with the initialValues value.

I'd like to know if anyone knows of the correct way to go about this? My way seems a bit hacky?

like image 125
Greg McKelvey Avatar answered Sep 18 '22 19:09

Greg McKelvey


Here is how i managed the hidden field value in Formik

Passed the setFieldValue as argument before the tage

{({ values, errors, touched, handleSubmit, setFieldValue , isSubmitting }) => (
<Form>
<div className="form-group has-feedback">
<input type="hidden" value="testing" name="hiddenField" />

Then I managed to changed it onClick method (can be used as required)

<button type="submit" className="btn btn-primary btn-block btn-flat" 
onClick={() => {setFieldValue("hiddenField", "yourValueHere OR dynamicVariable"); }} 
disabled={isSubmitting}>Register</button>
like image 33
Abdul Qadir R. Avatar answered Sep 17 '22 19:09

Abdul Qadir R.