Reputation: 23
I am a newbie to react
and I was not able to figure how to reset the checkbox to uncheck stat on resetting. I have used the react-bootstrap form
and need to reset the checkboxes to default state on a button click.
export const pitch: FC<pitchProps> = ({ pitchData, totalNoOfData }) => {
const [loading, setLoading] = useState(false);
const [totalRows, setTotalRows] = useState(totalNoOfData);
const formData = {
searchData: pitchParam.searchString,
searchCriteria: pitchParam.searchStatus,
};
const handleFormData = (e: any) => {
if (e.target.type === "checkbox") {
e.target.checked
? formData.searchCriteria.push(e.target.id)
: (formData.searchCriteria = formData.searchCriteria.filter(
(item: any) => item !== e.target.id
));
} else {
formData.searchData = e.target.value;
}
};
return (
<div className={styles.mainTableContainer}>
<div className="d-flex ml-2">
<Form className="w-100">
<Form.Row>
<Form.Label className={styles.label}>NEW </Form.Label>
<Form.Check
className={styles.checkbox}
type="checkbox"
id="OLD"
onChange={(e: any) => handleFormData(e)}
/>
<Form.Label className={styles.label}> OLD </Form.Label>
<Form.Check
className={styles.checkbox}
type="checkbox"
id="OUTDATED"
onChange={(e: any) => handleFormData(e)}
/>
<Form.Label className={styles.label}>OUTDATED </Form.Label>
<Form.Check
className={styles.checkbox}
type="checkbox"
id="SUCCESS"
onChange={(e: any) => handleFormData(e)}
/>
</Form.Row>
</Form>
</div>
</div>
);
};
Upvotes: 2
Views: 2252
Reputation: 8915
Your checkbox
component is not fully controlled by you, so it is an uncontrolled component.
As your checkbox
is controlled by the bootstrap-form you need to create a reference and pass it to the checkbox to manipulate the checked
value:
import React, {useRef} from 'react';
// reset of the codes
// in the pitch component
const checkboxRef = useRef(null);
Now, pass the checkboxRef
into the checkbox component within ref
property:
<Form.Check
type={type}
id={`default-${type}`}
label={`default ${type}`}
ref={checkboxRef} // <--------- here
/>
Now, try to add another button with a reset handler:
const handleResetCheckbox = () => {
checkboxRef.current.checked = false
}
You can also do the same with a different approach by using the React component's key. If the key gets changes, react will remove the component and create a new one. so you can use this key property to uncheck (reset) the checkboxes:
define a key
with useState
and pass it to the checkbox component:
const [key, setKey] = useState(false)
<Form.Check
key={key} // <--------- added here
type={type}
id={`default-${type}`}
label={`default ${type}`}
/>
Now, in the handleResetCheckbox
, change the key:
const handleResetCheckbox = () => {
setKey(prevState => !prevState)
}
So, when you reset the checkbox, the key will change then React will remove the old checkbox and render a new one. more information in React documentation.
Upvotes: 3