Skip to content

Instantly share code, notes, and snippets.

@warrenlalata
Last active June 11, 2022 22:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warrenlalata/fa0c810d5712b27d17a860d7017f629c to your computer and use it in GitHub Desktop.
Save warrenlalata/fa0c810d5712b27d17a860d7017f629c to your computer and use it in GitHub Desktop.
React Checkbox group with MUI
import React, { Component } from "react";
import { Field } from "redux-form";
import PropTypes from "prop-types";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Checkbox from "@material-ui/core/Checkbox";
export default class CheckboxGroup extends Component {
static propTypes = {
options: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.string.isRequired
})
).isRequired
};
field = ({ input, meta, options }) => {
const { name, onChange } = input;
const { touched, error } = meta;
const inputValue = input.value;
const checkboxes = options.map(({ label, value }, index) => {
const handleChange = (event) => {
const arr = [...inputValue];
if (event.target.checked) {
arr.push(value);
} else {
arr.splice(arr.indexOf(value), 1);
}
return onChange(arr);
};
const checked = inputValue.includes(value);
return (
<div key={`checkbox-${index}`}>
<FormControlLabel
className="checkbox-group-checkbox-label"
control={
<Checkbox
type="checkbox"
name={`${name}[${index}]`}
value={value}
checked={checked}
onChange={handleChange}
/>
}
label={label}
/>
</div>
);
});
return (
<div className="checkbox-group-container">
<div>{checkboxes}</div>
{touched && error && <p className="error">{error}</p>}
</div>
);
};
render() {
return <Field {...this.props} type="checkbox" component={this.field} />;
}
}
import CheckboxGroup from "Common/form/CheckboxGroup";
const options = [
{ label: "Non-Verified Users", value: "CONSUMER_BASICX" },
{ label: "Verified Users", value: "CONSUMER_UPGRADEDX" },
{ label: "Negosyo Users", value: "TRADEX" }
];
<CheckboxGroup name="target_users" options={options} />
@tombohub
Copy link

thanks, do you also have one where it goes like this?:

<CheckboxGroup>
  <Checkbox/>
  <Checkbox/>
</CheckboxGroup>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment