Search code examples
javascriptreactjsreact-admin

How to translate the content of a <SelectInput /> or any other components?


In react admin v3,

I am sending from the servers within my entity a slug.

The slug is a key that should be assigned to a translation client side.

This is my <CallMeBackCreate /> component:

    <Create {...props}>
      <SimpleForm>
        <ReferenceInput
          source="status.id"
          reference="callmeback"
        >
          <SelectInput optionText="description" />
        </ReferenceInput>
      </SimpleForm>
    </Create>

Instead of using the description I would like to use the slug and translate client side,

For example this is a list of this entity:

[
  {
    "description": "Refused",
    "slug": "refused"
  },
  {
    "description": "Accepted",
    "slug": "accepted"
  },
  {
    "description": "Abandoned",
    "slug": "abandoned"
  },
  {
    "description": "Wrong number",
    "slug": "wrong-number"
  },
  {
    "description": "To renew call back",
    "slug": "to-renew-call-back"
  },
  {
    "description": "To call back",
    "slug": "to-call-back"
  }
]

I expect to use the slug to translate in FR and EN, how is this possible?


Solution

  • SelectInput alone has a optional prop translateChoice that defaults to true, but i don't know what value is set by parent ReferenceInput, if any.

    SelectInput optionText also accepts a function, receiving the choice and expecting string result.

    So you can try this:

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

    import { useTranslate } from 'react-admin'
    
    export const CallMeBackCreate  = props => {
    
    const translate = useTranslate()
    
    return (
       <Create {...props}>
          <SimpleForm>
            <ReferenceInput
              source="status.id"
              reference="callmeback"
            >
              <SelectInput
                  optionText={choice => translate(choice.slug)}
                  //OR translateChoice={true} optionText="slug"
              />
            </ReferenceInput>
          </SimpleForm>
        </Create>
    )
    }