Last active
June 11, 2022 22:50
-
-
Save warrenlalata/fa0c810d5712b27d17a860d7017f629c to your computer and use it in GitHub Desktop.
React Checkbox group with MUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} />; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} /> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks, do you also have one where it goes like this?: