So I am using Formik and MUI. I am unable to reset checkbox values after submitting.
I have tried useRef, states, setFieldsValue to manipulate this. But no luck. (I might be doing something in the wrong way probably)
Let me know if there is any mistake or workaround that I am missing. Or if you have any suggestions for this.
Below is the code that can be refferred.
Main Form
const LeadForm = () => {
const [loc, setLoc] = useState({});
const handleSubmitForm =(values, formik) =>{
let googleLocation = [];
Object.keys(loc).forEach((e) => {
loc[e]===true && googleLocation.push(e);
})
const postData={
user_google_location: googleLocation.join(','),
}
Axios.post(`...url`, qs.stringify(postData))
.then(response =>{
...some toast
}).catch(err=>console.log(err))
}
let location = [
{
id: 1,
typeValue: Delhi
},
{
id: 2,
typeValue: Punjab
}
]
return (
<div className={Styles.FormDiv}>
<Formik
initialValues={{
user_google_location:''
}}
onSubmit={ (values) => {
handleSubmitForm(values);
}}
>
{({
values,
errors,
handleChange,
handleSubmit,
}) => {
return <Form onSubmit={handleSubmit}>
{
location.map((e, index) =>
<div key={index}>
<CheckBoxSelectors
id={e.id}
values={values}
setLoc={setLoc}
loc={loc}
label={e.typeValue}
/>
</div>
)
}
<button type="button" className={Styles.SubmitButton}
onClick={() => {
handleSubmitForm(values);
handleReset();
}}
>
SUBMIT
</button>
</Form>}
}
</Formik>
</div>
)
};
export default LeadForm;
CheckBoxSelectors Component
import React, {useEffect} from 'react';
import { withStyles } from '@material-ui/core/styles';
import FormGroup from '@material-ui/core/FormGroup';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
const BlueCheckbox = withStyles({
root: {
'&$checked': {
color: "#1c75c0",
},
},
checked: {},
})((props) => <Checkbox color="default" {...props} />);
export default function CheckboxLabels(props) {
const {label, values, id, loc, setLoc} = props
const handleChange = (event, value) => {
let obj = {};
obj[event.target.name] = event.target.checked;
setLoc({...loc, ...obj});
};
return (
<div>
<FormGroup>
{...normal div...}
<FormControlLabel
control={
<BlueCheckbox
checked={values[checkBox[0].name]}
onChange={handleChange}
name={checkBox[0].name}
color="primary"
/>
}
/>
</FormGroup>
</div>
);
}
3
Answers
Solved by my own!
CheckBoxSelectors Component
For the time being this is working. Still open to any suggestions if any.
https://formik.org/docs/api/formik#resetform-nextstate-partialformikstatevalues–void
I think that it can help your case.
e/g:
or
Remove the
onChange
fromcheckbox
and add inFormControlLabel
. I did in my project like this: