How to fix Type Props Error when onChange Event in Formik/Field Input - reactjs

When I want to trigger the onChange event of Formik/Field(input).
I don't know how to trigger the onChange Event in Formik/Field. So I tried to trigger onChange event in Formik/Form and get the id of event params. But it is facing the problem of Props in Typescript.
Please check my code snippet and let me know how to fix this problem. Thanks in advance.
const InputCustomerForm = () => {
...
const handleFormChange = (event: FormEvent) => {
if (event.target.id === "mobileNumber"){
const value = phoneConvertor(event.target.value);
setUpdatedPhoneNumber(value);
}
}
return (
<OrderPaymentFormContainer className={`${showAccount === true ? 'show' : 'hidden'}`}>
<Formik
initialValues={initialValues}
enableReinitialize={true}
validationSchema={OrderPaymentFormSchema}
onSubmit={(values, actions) => {
handleSendEmail(values);
actions.setSubmitting(false);
}}
>{
({ handleSubmit, errors, touched, isValid }) => (
<Form onSubmit={handleSubmit} onChange={handleFormChange}>
...
<div>
<label>
Mobile Phone Number
</label>
<div>
<div>
<Field id="countryCode" name="countryCode" as="select">
<option defaultValue="1">US</option>
</Field>
</div>
<div>
<Field id="mobileNumber" name="mobileNumber" placeholder="(201) 555-0123" value={updatedPhoneNumber}/>
</div>
</div>
{errors.mobileNumber && touched.mobileNumber ?
(<div className="order-detail--card-form-item-error">{errors.mobileNumber}</div>) : null
}
</div>
...
</Form>
)
}
</Formik>
</OrderPaymentFormContainer>
)
}
export default InputCustomerForm;
As we can see, I hope to get the changed value of input and want to do some function with changed values and return to Input's current value. But it's not working now. Please let me know the problem how to resolve this problem. Thanks
I tried it by manually using pure function but it's not working.
I hope to resolve this problem in typescript.

Related

React final form triggers handleSubmit after the initial render

I've got only Switch component in my react-final-form. It looks like this:
<Form
onSubmit={onSubmit}
initialValues={initialValues}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<Field name="booleanValue" component={Switch} onChange={handleSubmit}/> //triggers when receives value
</form>
)
}
/>
I want to trigger handleSubmit only after user changes, not at first render of the form.
<Field/> doesn't have an onChange prop like you are attempting. Something like this could work.
import { OnChange } from 'react-final-form-listeners'
...
<Form
onSubmit={onSubmit}
initialValues={initialValues}
render={({ handleSubmit, form }) => (
<form onSubmit={handleSubmit}>
<Field name="booleanValue" component={Switch}/>
<OnChange name="booleanValue">
{(value, previousValue) => {
form.submit()
}}
</OnChange>
</form>
)
}
/>
P.S. I hope your Switch component knows to get its value and onChange from the input prop.
Hope that helps!

Clear a field's value on input clear in react-final-form

I'm using a custom component with react-final-form. On input change it sets the value to the address field. But when the input is cleared it doesn't update the value of the field. So I'm trying to do it with form mutators.
I have already added a mutator for clearing the field:
mutators={{
clear: ([address], state, { changeValue }) => {
changeValue(state, "address", () => undefined);
}
}}
I tried to add it to my custom onChange function, but it doesn't work.
onChange={event =>
props.input.onChange !== undefined
? props.input.onChange({ value: event })
: form.mutators.clear
}
Or maybe this can be done without mutators at all? I would really appreciate your help. Here is a live example (clearing the field works only on the button click as onClick={form.mutators.clear}).
You can just call form.change('address', undefined) at any time that you'd like to clear the value.
All the default callback are handle by the component. If you want to do a clear with a button click, you can create a custom component and use native callback methods do your thing.
onChange = (event) => {
this.setState({
address:event.target.value
});
}
onClear = () => {
this.setState({
address:''
});
}
<div>
<Field name="address">
<div>
<input
value={this.state.address}
onChange={this.onChange}
/>
</div>
</Field>
<button onClick={this.onClear}>Clear</button>
</div>
The problem is not with the react-final-form in your code, it is due to the react-da data, I have played a lot around your code within 1 day, and checked reset is working with fine with the react-final-form
Just update your render with this code and see reset is working absolutely fine. Yeah! the problem is with react da data. I am not sure about what it does due to less official information for this package.
<div className="App">
<h2>Dadata test</h2>
<Form
mutators={{
clear: ([address], state, { changeValue }) => {
changeValue(state, "address", () => undefined);
}
}}
onSubmit={onSubmit}
render={({ form, handleSubmit, pristine, invalid, values, errors }) => (
<form onSubmit={handleSubmit} noValidate>
<Field name="address" component="input" />
{/* {props => (
<div>
<ReactDadata
token="d19c6d0b94e64b21d8168f9659f64f7b8c1acd1f"
onChange={event =>
props.input.onChange !== undefined
? props.input.onChange({ value: event })
: form.mutators.clear
}
/>
</div>
)}
</Field> */}
<button type="submit" disabled={invalid}>
Submit
</button>
<button type="button" onClick={form.reset}>
Clear
</button>
<Fields names={["address"]}>
{fieldsState => (
<pre>{JSON.stringify(fieldsState, undefined, 2)}</pre>
)}
</Fields>
</form>
)}
/>
</div>
Hope it will help you to resolve the problem.

How to reset antd datepicker after submiting a value?

here i am providing my sample example working on codesandbox. How to reset a datepicker value after submitting a form?
state = {
setFieldValue: ''
}
onChange = (setFieldValue) => {
this.setState({ setFieldValue: null })
}
render() {
const { values, handleSubmit } = this.props
return (
<div align="center">
<Form onSubmit={handleSubmit}>
<Field
name="dateofbirth"
label="dateOfBirth"
component={DateInput}
formitemlayout={formItemLayout}
value={this.state.setFieldValue}
onChange={this.onChange}
/>
<Button type="primary"
htmlType="submit">Submit</Button>
}
my working codesandbox link is enter link description here
Instead of adding empty strings as it raises a propType error its best to use null
<DatePicker
onChange={(date, dateString) =>
setFieldValue("dateofbirth", dateString)
}
value={dateofbirth !== "" ? moment(dateofbirth) : null}
/>
Your Datepicker is not a controlled component. I converted it to a controlled component and date field was reset post form submission.
<DatePicker
onChange={(date, dateString) =>
setFieldValue("dateofbirth", dateString)
}
value={dateofbirth !== "" ? moment(dateofbirth) : ""}
/>
Codesandbox link

Can't update form inside of onBlur in redux-form

I have a field AskQuestions where a user enters something and a dropdown appears on each user keystroke with updated results in an array, companyOptions. However, when a user clicks out of a field I am trying to clear current field's value via this.props.dispatch(change..)) but this seems impossible.
<Field
name="company"
type="text"
onBlur={this.onClearSearch}
keyUp={this.renderCompanyList}
component={renderField}
label="Choose Company..."/>
here is my renderField
function renderField(field) {
const { meta: {touched, error} } = field;
return(
<div>
<input type={field.type}
placeholder={field.label}
onKeyUp={field.keyUp ? () => {field.keyUp(field.input.value)} : ""}
onBlur={field.onBlur ? () =>{field.onBlur()} : ""}
{...field.input}
// I also tried putting in after ...input
// onBlur={field.onBlur ? () =>{field.onBlur()} : ""}
/>
<div className="text-danger">
{touched ? error : ''}
</div>
</div>
);
}
I have the following callback associated, but this.props.dispatch does not reset the field.
onClearSearch(){
this.props.dispatch(change('AskQuestion','company',''));
}
it's because there are an default event onBlur which modifies the value of the input after having been modified by your function onClearSearch,
Add an e.preventDefault() at the end of onClearSearch will have to solved your problem, something like this:
onClearSearch(e){
const {companyOptions} = this.state;
if (companyOptions.length){
var company = companyOptions[0];
this.props.dispatch(change('AskQuestion','company',company.label));
}
else {
this.props.dispatch(change('AskQuestion','company',''));
}
// hides the dropdown view
this.setState({showCompanySearch:false})
// here
e.preventDefault();
}
More info here
I hope this can help you

How to get field values from redux-form

I am unable to get field values in my submit callback. Instead I am receiving an event there.
Can anybody tell me what I am doing wrong
render() {
const { fields, handleSubmit, submitting, buttonWrapper, btnText } = this.props;
return (
<form name="AddEvent" onSubmit={handleSubmit}>
{fields.map(field => (
<div className={field.wrapperClass}>
<Field
name={field.name}
type={field.type || 'text'}
component={mapComponentClass(field.componentClass)}
validate={mapValidators(field.validate)}
props={field.inputProps}
label={field.label}
/>
</div>
))}
<div className="form-submit-wrap container">
<button
type="submit"
disabled={submitting}
className="form-submit"
>
{submitting ? 'Submitting' : 'Submit'}
</button>
</div>
</form>
);
}
handleSubmit is supposed to be a wrapper of your onSubmit function.
Try it like this:
<form onSubmit={handleSubmit(onSubmit)}>
</form>
Now onSubmit will receive 1 argument with all the form values.
Not that you asked for it, but as a side note, if you want, you can trigger a submit validation error from inside your onSubmit function like:
throw ReduxForm.SubmissionError({name: 'There\'s something wrong in the name field'});
... as a result of your Ajax call to make name invalid.

Resources