I have a CheckboxGroupInput
field like this:
<CheckboxGroupInput source="fruits" choices={[
{ 'name': 'apples' },
{ 'name': 'pears' }
]} optionValue='name'/>
which produces json likes this for the fruits
field when the user selects both options:
'fruits': ['apples','pears']
I want to display it in a List
using ChipField
which requires a source
which I don't have, because the json is a plain string array.
source would be "name" if json looked like fruits:[{'name':'apples'}, {'name':'pears'}]
<ArrayField source='fruits'>
<SingleFieldList>
<ChipField source='???' />
</SingleFieldList>
</ArrayField>
How can I show the contents of a plain string array with ChipField
OR how do I tell CheckboxGroupInput
to produce an object array instead of a string array?
It is always a good idea to look at demo code. I managed to create a custom component called SimpleChipField
by modifying a custom ChipField
from the react-admin demo code. It shows the entire record
as label.
import React from 'react';
import Chip from '@material-ui/core/Chip';
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles({
main: {
display: 'flex',
flexWrap: 'wrap',
marginTop: -8,
marginBottom: -8,
},
chip: { margin: 4 },
});
const SimpleChipField = ({ record }) => {
const classes = useStyles();
return record ? (
<span className={classes.main}>
<Chip
key={record}
className={classes.chip}
label={record}
/>
</span>
) : null;
};
SimpleChipField.defaultProps = {
addLabel: true,
};
export default SimpleChipField;
To use it, just put it instead of the regular ChipField
.
<ArrayField source="fruits">
<SingleFieldList>
<SimpleChipField />
</SingleFieldList>
</ArrayField>