Home > Net >  React - how to use i18nNext in antd table
React - how to use i18nNext in antd table

Time:09-09

It is the current UI enter image description here

App.tsx

import "./styles.css";

import MyTable from "./MyTable";

export default function App() {
  const data = [
    {
      key: "1",
      date: "2022-01-01",
      description: "Description 1",
      url: "#"
    }
  ];
  return <MyTable data={data} />;
}

MyTable.tsx

import React from "react";
import { useTranslation } from "react-i18next";
import { Table } from "antd";
import type { ColumnsType } from "antd/es/table";

export interface TableDataType {
  key: string;
  description: string;
  url: string;
  date: string;
}

const columns: ColumnsType<TableDataType> = [
  {
    title: "template.date",
    dataIndex: "date",
    key: "date"
  },
  {
    title: "template.description",
    dataIndex: "description",
    key: "description"
  },
  {
    key: "url",
    render: (_, data) => (
      <a href={data.url} target="_blank" rel="noreferrer">
        Download Now
      </a>
    )
  }
];

interface MyTableProp {
  data: TableDataType[];
}

const MyTable = ({ data }: MyTableProp) => {
  const { t } = useTranslation();

  return (
    <Table
      columns={columns.map((column) => {
        return {
          ...column,
          title: t(column.title as string)
        };
      })}
      dataSource={data}
      pagination={false}
    />
  );
};

export default MyTable;

I can use the translation for columns like

  {
    title: "template.date",
    dataIndex: "date",
    key: "date"
  },
  {
    title: "template.description",
    dataIndex: "description",
    key: "description"
  },

I'm wondering how I can use the translation like t('a-i18n-key') for the Download Now button Column, seem it's not a JSX component.

  {
    key: "url",
    render: (_, data) => (
      <a href={data.url} target="_blank" rel="noreferrer">
        Download Now
      </a>
    )
  }

Does anyone has idea?

Codesandbox
https://codesandbox.io/s/react-typescript-forked-1c1407?file=/src/MyTable.tsx

CodePudding user response:

You can import your i18n file where you defined your locales and translate it with that.

import i18n from "./path/to/your/i18n/definition";

and then use it like this outside components:

      <a href={data.url} target="_blank" rel="noreferrer">
{i18n.t("Download Now translation")}
     </a>

Just make sure you match the import with how you export your i18n code.

  • Related