UNPKG

@shakthillc/components

Version:

React generic components for shakthi products

91 lines (86 loc) 2.46 kB
import React from "react"; import PropTypes from "prop-types"; import style from "./CheckBoxGroup.module.css"; export default class CheckBoxGroup extends React.Component { constructor(props) { super(props); this.state = { isChecked: [], }; this.onChange = this.onChange.bind(this); } componentDidMount() { const { options } = this.props; let isChecked = options.map((obj) => { if (Object.keys(obj).includes("flag")) { return obj; } else { return Object.assign(obj, { flag: false }); } }); console.log(isChecked); this.setState({ isChecked }); } onChange(targetFlag, targetValue) { var { isChecked } = this.state; var { onChange } = this.props; let modifiedIsChecked = isChecked.map((obj) => { if (obj.value == targetValue) { return Object.assign(obj, { flag: targetFlag }); } else { return obj; } }); let returnValue = []; isChecked.map((obj) => { if (obj.flag) { returnValue.push(obj.value); } }); this.setState({ isChecked: modifiedIsChecked, }); onChange && onChange(returnValue); } render() { let { disabled, options } = this.props; let { isChecked } = this.state; let optionHtml = isChecked.map((obj, i) => { return ( <label key={i} className={style["check-box__each"]}> {obj.label.length > 0 ? obj.label : obj.value} <input type="checkbox" name="checkbox" onChange={(e) => this.onChange(e.currentTarget.checked, obj.value)} checked={obj.flag} /> <span className={style["check-box__checkmark"]} value={obj.label} id={obj.value} ></span> </label> ); }); return <div className={style["check-box"]}>{optionHtml}</div>; } } CheckBoxGroup.defaultProps = { options: [ { value: "option1", label: "Option 1", flag: true }, { value: "option2", label: "Option 2" }, { value: "option3", label: "Option 3" }, { value: "option4", label: "Option 4", flag: true }, ], onChange: (data) => { console.log(data); }, }; CheckBoxGroup.propTypes = { disabled: PropTypes.bool, options: PropTypes.arrayOf({ value: PropTypes.string, label: PropTypes.number, }), };