reactjstypescriptreact-intl

react-intl: formatMessage for array of string


enter image description here

I have several interfaces, and among these interfaces there is an interface for "displaying users", and there is a field called "Role", which represents an array of user roles, And I want to translate this column, and it was actually translated through these lines:

            tableDataMapper={(rows) => {
                    return rows?.map((row: any, index) => {
                        console.log('row: ', rows);
                        return {
                            ...row,
                            roleNames: formatMessage({
                                id: formatMessage({ id: row?.roleNames }),
                            })
                        };
                    });
                } }

But the problem is that if the array contains more than one element, it does not translate it, like this picture, it translates all lines except for the line indicated in red.

enter image description here

import { FunctionComponent, useContext } from 'react';
import user from '../../../../api/nuclearMedicineApi/services/User/index';
import Scaffold from '../../../common/scaffold';
import UserForm from './form/index';
import { userColumns } from './data';
import { selectMapper } from '../../../../utils/mappers';
import moment from 'moment';
import { indexFilters } from './filters';
import { useQuery } from 'react-query';
import {
    AuthContext,
    IAuthContext,
} from '../../../../contexts/auth-context';
import { FormattedMessage, useIntl } from 'react-intl';


interface UsersProps { }

const Users: FunctionComponent<UsersProps> = () => {

    const { formatMessage } = useIntl();

    const auth = useContext<IAuthContext>(AuthContext);

    const filterOptionsData = useQuery('userFilterOptions', () =>
        [{key: 'key', value: 0, label: 'label' }],
    );

    let userListColumns = userColumns;
    userListColumns = auth.userData?.roleNames?.some(
        (role) => role !== 'ADMIN',
    )
        ? userListColumns.filter(
            (item) => item.dataSelector !== 'roleNames',
        )
        : userListColumns;
        
    return (
        <>
            <Scaffold
                createFunc={user.userCreate}
                getFunc={user.userGet}
                getAllFunc={user.userGetAll}
                filterColumns={indexFilters}
                updateFunc={user.userUpdate}
                deleteFunc={user.userCreate}
                switchActivation
                create
                switchActivationFunc={user.userSwitchActivation}
                tableColumns={userListColumns}
                filterOptions={filterOptionsData.data}
                dataName='user'
                formContent={UserForm}
                fullWidthFrom
                exportToExcelFunc={user.userGetExcelReport}
                defaultSizePaination={10}
                pageSizeOptions={[10, 20, 50, 100]}
                FormSubmitMapper={(data) => {


                    return {
                        ...data,
                        password: data.password ?? null,
                        ...selectMapper(['patientId', 'patient'], data),
                    };
                } }
                tableDataMapper={(rows) => {
                    return rows?.map((row: any) => {
                        console.log('row: ', rows);
                        return {
                            ...row,
                            roleNames: formatMessage({
                                id: formatMessage({ id: row?.roleNames }),
                            })
                               
                    
                        };
                    });
                } }
                FromDataMapper={(data) => {
                    return {
                        ...data,
                        lastModificationTime: moment(
                            new Date(data.lastModificationTime)
                        ).format('YYYY-MM-DD, h:mm a'),
                        creationTime: moment(
                            new Date(data.creationTime)
                        ).format('YYYY-MM-DD, h:mm a'),
                    };
                } }
                mainPermissionName='User' approveFunc={function (data: any): Promise<any> {
                    throw new Error('Function not implemented.');
                } } rejectFunc={function (data: any): Promise<any> {
                    throw new Error('Function not implemented.');
                } }            />
        </>
    );
};

export default Users;

Solution

  • I assume that you want to display the translations of individual roles separated by commas (e.g if A translates to roleA and B translates to roleB, roleNames: ["A", "B"] should be displayed as "roleA, roleB").

    Since you have roleNames: ["SystemAdmin", "NationalRegistry"], you could simply do roleNames.map(roleName => formatMessage({ id: roleName })).join(', ')