Ahmed Elbessfy
Ahmed Elbessfy

Reputation: 145

Using Lingui with dynamic form generator

I have a dynamic form generator which accepts JSON object, and then creates a form with its fields. JSON objects consist of separate objects each describing form fields.

I am trying to use Lingui to localize and translate the content of each field, including labels, placeholder, options and error messages.

My main problem is that I can't find a way to translate variables used to represent content.

Here is an example - this is a sample configuration for 2 select fields:

{
    category: "field",
    fieldType: "select",
    id: "appointmentType",
    testId: "appointmentType",
    name: "appointmentType",
    label: "Type",
},
{
    category: "field",
    fieldType: "select",
    id: "other",
    testId: "other",
    name: "other",
    label: "Subtype",
},

And here are my approaches:

<label>{label && <Trans>{label}</Trans>}</label>

//

<label>{label && t(i18n)`${label}`}</label>

What I need to know is how to make Lingui translate various values of labels. Any help is appreciated.

Upvotes: 0

Views: 178

Answers (1)

Ahmed Elbessfy
Ahmed Elbessfy

Reputation: 145

After a bit of research and help, I found a workaround using Lazy Translation. Solution is to define the content using "msg" macro, and it will be added to Translation resources with its Id and I can use the translated text using the "i18n._" method.

Here is a sample:

import { msg } from "@lingui/macro";

{
    category: "field",
    fieldType: "select",
    id: "appointmentType",
    testId: "appointmentType",
    name: "appointmentType",
    label: msg`Type`,
},
{
    category: "field",
    fieldType: "select",
    id: "other",
    testId: "other",
    name: "other",
    label: msg`Subtype`,
},


// and its usage like this:
import { i18n } from "@lingui/core";

<label>{i18n._(label)}</label>

I hope this helps anyone stuck in similar situations.

Upvotes: 1

Related Questions