Is there a recommended way of having the value of a field as an array and using checkboxes to populate the array?
For example, in the live demo you have toppings like pepperoni, mushroom, ham etc. and these are all just fields with separate names. However, if one wanted to have the value of these stored in an array under a separate key, 'toppings', what's the way to do this?
I'm basically wanting to replicate a HTML checkbox input like:
<input type="checkbox" name="toppings[]" value="mushrooms">
<input type="checkbox" name="toppings[]" value="pepperoni">
Its wath i did for it :
Render.js
import Checkbox from 'material-ui/Checkbox'; /** /* @param options {object[]} /* @param options.label {string} /* @param options.value {any} */ export const renderCheckboxGroup = ({ name, options, input, meta, ...custom}) => { let $options = options.map((option, i) => ( <div key={i}> <Checkbox name={`${name}[${i}]`} defaultChecked={input.value.indexOf(option.value) !== -1} label={option.label} onCheck={(e, checked) => { let newValue = [...input.value]; if (checked){ newValue.push(option.value); } else { newValue.splice(newValue.indexOf(option.value), 1); } return input.onChange(newValue); }} {...custom} /> </div> )); return ( <div> {$options} </div> ); };
And how to use it :
ToppingCheckBoxGroup.view.jsx
import {renderCheckboxGroup} from 'Renderers'; class ToppingCheckBoxGroup extends React.Component { render() { return ( <fieldset> <legend>Toppings</legend> <Field name="toppings" component={renderCheckboxGroup} options={this.props.toppings} /> </fieldset> ); } } ToppingCheckBoxGroup.propTypes = { toppings: React.PropTypes.arrayOf( React.PropTypes.shape({ label: React.PropTypes.string.isRequired, value: React.PropTypes.any.isRequired }) ).isRequired, };
I'll add this in example. @zazapeta Thank you for example.
Most helpful comment
Its wath i did for it :
And how to use it :