'React reusable form group checkboxes component need to pass an array object with its props
I am trying to create a reusable form group component that I can use anywhere in the app I have used material-ui and formik. This is the reusable form group component that I created
import {
Checkbox,
FormControl,
FormControlLabel,
FormGroup,
FormLabel,
FormHelperText } from '@material-ui/core';
import { useField, useFormikContext } from 'formik';
const CheckboxesGroup = ({
name,
label,
legend,
...otherProps
}) => {
const { setFieldValue } = useFormikContext();
const [field, meta] = useField(name);
// const { morning_slot, afternoon_slot, evening_slot } = field;
// const error = [morning_slot, afternoon_slot, evening_slot].filter((v) => v).length < 1;
const handleChange = (evt) => {
const { checked } = evt.target;
setFieldValue(name, checked);
};
const configCheckbox = {
...field,
onChange: handleChange
};
const configFormControl = {
error:{error},
component:"fieldset",
sx:{ m: 3 },
variant:"standard"
};
if (meta && meta.touched && meta.error) {
configFormControl.error = true;
}
return (
<FormControl {...configFormControl} >
<FormLabel component="legend">Time-Slot</FormLabel>
<FormGroup>
<FormControlLabel
control={<Checkbox {...configCheckbox} />}
label={label}
/>
</FormGroup>
<FormHelperText>Select altleast one Slot</FormHelperText>
</FormControl>
);
}
export default CheckboxesGroup;
and i need help to pass this from the Form.js file
facility = [
{id: 'morning_slot', name: 'morning_slot', label: 'Morning Slot [5AM-10PM]'},
{id: 'afternoon_slot', name: 'afternoon_slot', label: 'Afternoon Slot [12PM-4PM]'},
{id: 'evening_slot', name: 'evening_slot', label: 'Evening Slot [5PM-10PM'}
];
to that component and I don't know if there is a need for mapping or not. can someone look into this and reply with the corrected code
Solution 1:[1]
When you call the component from the File.js and pass the props like this:
<CheckboxesGroup prop_name=facility ><\CheckboxesGroup>
And get the your props in the CheckboxesGroup function:
const CheckboxesGroup = (props) => {
.....
const myfacility = props.prop_name;
// myfacility should look like the facility props you passed from the `File.js`
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Itik |
