How to reset antd datepicker after submiting a value? - reactjs

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

Related

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

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.

Set defaultValues to Controllers in useFieldArray

Misunderstanding react-hook-forms.
I have a form for editing some stuff. Form contains fieldArray.
I set initial formData in useForm hook using default values
const methods = useForm({ defaultValues: defaultValues });
where defaultValues is
const defaultValues = {
test: [
{
name: "useFieldArray1"
},
{
name: "useFieldArray2"
}
]
};
And fieldArray. Here I'm using Controller (it's simplified case - in fact Custom input Controller more complex)
<ul>
{fields.map((item, index) => {
return (
<li key={item.id}>
<Controller
name={`test[${index}].name`}
control={control}
render={({value, onChange}) =>
<input onChange={onChange} defaultValue={value} />}
/>
<button type="button" onClick={() => remove(index)}>
Delete
</button>
</li>
);
})}
</ul>
When form is rendered everything is fine. Default values are displayed in input fields. But when I delete all fields and click append - new fields are not empty ... Default values are displayed
again. And it happens only with Controller. Why it happens ? And how I can avoid it?
Please, here is CodeSandBox link. Delete inputs and press append to reproduce what I am saying.
https://codesandbox.io/s/react-hook-form-usefieldarray-nested-arrays-forked-7mzyw?file=/src/fieldArray.js
Thanks
<Controller
name={name}
rules={rules}
defaultValue={defaultValue ? defaultValue : ''}
render={({ field, fieldState }) => {
return (
<TextField
inputRef={field.ref}
{...props}
{...field}
label={label}
value={field.value ? field.value : ''}
onChange={(event) => {
field.onChange(event.target.value);
props.onChange && props.onChange(event);
}}
style={props.style || { width: '100%' }}
helperText={fieldState?.error && fieldState?.error?.message}
error={Boolean(fieldState?.error)}
size={props.size || 'small'}
variant={props.variant || 'outlined'}
fullWidth={props.fullWidth || true}
/>
);
}}
/>

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.

Using react-datepicker alongside redux-form?

I'm trying to use redux-form along with react-datepicker but keep getting the following error:
Warning: Failed prop type: Invalid prop `value` of type `object` supplied to `DatePicker`, expected `string`.
I have my code setup as follows:
renderDatePicker({input, placeholder, defaultValue="01/01/2018", meta: {touched, error} }) {
return (
<div>
<DatePicker {...input} dateForm="MM/DD/YYYY" selected={input.value ? moment(input.value) : null} />
{touched && error && <span>{error}</span>}
</div>
)
};
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.submit.bind(this))}>
<Field name='budgetDateDue' component={this.renderDatePicker} format={(value, name) => value || null} />
<button type='submit'>Submit</button>
</form>
)
}
I can't seem to get around this Warning and I haven't found much online aside from what I have already done.
input is an object, and input.value is a moment object. <DatePicker /> is expecting a string, so you'll need to pass it one. Convert the moment object to a string (and format it however you want).
<DatePicker
{...input}
value = {moment(input.value).format('MM-YYYY')}
dateForm = "MM/DD/YYYY"
selected = {input.value ? moment(input.value) : null}
/>
You can create a custom datepicker and pass props to it
const datePicker = ({ input, label, type, className, selected, meta: { touched, error } }) => (
<div>
<div>
<DatePicker {...input}
selected={selected}
placeholder={label}
type={type}
className={className}
dropdownMode="select"
/>
{touched && error && <span className="error_field">{error}</span>}
</div>
</div>
)
And in redux-form component you can do something like this
<Field
name="date_of_birth"
component={datePicker}
type="text"
selected={this.state.date_of_birth}
onChange={this.handleChange.bind(this)}
className="form-control"
/>
Any of the samples below worked for me, this was my solution:
class DateField extends Component {
render() {
const {
input,
meta: { error, touched },
} = this.props;
return (
<div>
<DatePicker
{...input}
dateForm="MM/DD/YYYY"
selected={input.value && input.value}
onChange={time => {
input.value = time ? time : null;
}}
onBlur={() => input.onBlur(input.value)}
/>
{touched && error && <span className="error-block">{error}
</span>}
</div>
);
}
}
export default DateField;
Then wrap this in a Form element.

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

Resources