Search code examples
react-admin

How to use a dynamic optionText?


We have the following that displays a select style UX:

    <ReferenceInput source="visibility.visibilityId" reference="projectVisibilities" allowEmpty>
      <SelectInput optionText="visibility" />
    </ReferenceInput>

We want to add in parentheses the description within visibility.

Something like this :

    <ReferenceInput source="visibility.visibilityId" reference="projectVisibilities" allowEmpty>
      <SelectInput optionText={["visibility", "(", "description", ")" } />
    </ReferenceInput>

An unfound string would be rendered as a regular string and visibility and description as the optionText of the select input, after joining the array.

Is this something already possible?


Solution

  • optionText accepts a function, so you can shape the option text at will:

    const optionRenderer = choice => `${choice.visibility} (${choice.description})`;
    
    <SelectInput optionText={optionRenderer} />
    

    optionText even accepts a React Element, that will be cloned and receive the related choice as the record prop. You can use Field components there:

    const DescriptionField = ({ record }) => <span>{record.visibility} ({record.description})</span>;
    
    <SelectInput optionText={<DescriptionField />}/>
    

    Note that this is clearly documented in the React-admin documentation:

    https://marmelab.com/react-admin/Inputs.html#selectinput