React-admin Array input with array of strings/numbers React-admin Array input with array of strings/numbers arrays arrays

React-admin Array input with array of strings/numbers


I was able to execute the inputs variant, as opposed to the fields variant, by simply not providing a source attribute for the inner TextField, and sourcing the array in the actual ArrayField. Then of course just use a SimpleFormIterator. Clearly React favors the use of keys, treating array types like maps, for the most part.

<ArrayInput source="my-source">  <SimpleFormIterator>    <TextInput />  </SimpleFormIterator></ArrayInput>


Here is my working code based on @fzaninotto's post in react-admin Issues:

import Chip from '@material-ui/core/Chip'const TextArrayField = ({ record, source }) => {  const array = record[source]  if (typeof array === 'undefined' || array === null || array.length === 0) {    return <div/>  } else {    return (      <>        {array.map(item => <Chip label={item} key={item}/>)}      </>    )      }}TextArrayField.defaultProps = { addLabel: true }

Usage:

  <TextArrayField source="tags">    <SingleFieldList>      <ChipField source="id" />    </SingleFieldList>  </TextArrayField>


Maybe you can create your own Field component which can able to take source and record as props.

 function populateList(numbers) {        return numbers.map((number) =>            <li key={number.toString()}>                {number}            </li>        );    }    const SimpleArray = ({source, record = {}}) =>        <ul>            {                populateList(record[source])            }        </ul>;    SimpleArray.defaultProps = {        addLabel: true,        label: 'List'     };    SimpleArray.propTypes = {        label: PropTypes.string,        record: PropTypes.object,        source: PropTypes.string    };    export default SimpleArray;

And easily use it inside any form element like :

  <SimpleShowLayout>                        <TextField source="id"/>                        <TextField label="Title" source="title" className={classes.name}/>                         <TextField source="title"/>                        <NumberField source="defaultItemCount"/>                        <RichTextField source="description"/>                        <NumberField source="priceInNumber"/>                        <SimpleArray source="attributeArray" label="Product Attributes" />                    </SimpleShowLayout>