reactjsdatatabletranslate

React - How to change the language of DataTable component properties of material ui?


I'm using a Material ui component called DataTable, the problem is that filter fields are in English and I was wondering if there is any way to change their language to Portuguese

below my component code:

import * as React from 'react';
import { DataGrid } from '@mui/x-data-grid';
import { PropTypes } from 'prop-types';

export default function DataTable({ rows, columns }) {
  return (
    <div style={{ height: 400, width: '100%' }}>
      <DataGrid
        rows={rows}
        columns={columns}
        pageSize={5}
        rowsPerPageOptions={[5]}
        checkboxSelection
      />
    </div>
  );
}

DataTable.propTypes = {
  rows: PropTypes.arrayOf(
    PropTypes.shape({
      conteudo: PropTypes.string,
      disciplina: PropTypes.string,
      curso: PropTypes.string,
      data: PropTypes.string,
    })
  ).isRequired,
  // eslint-disable-next-line react/forbid-prop-types
  columns: PropTypes.array.isRequired,
};

enter image description here

I want to translate "unsort, sort by Desc, Filter, Hide..." to english


Solution

  • You can localize any text label on DataGrid by passing a localeText object prop to the DataGrid like this:

    import { useState } from "react";
    import { DataGrid } from "@mui/x-data-grid";
    
    const localizedTextsMap = {
      columnMenuUnsort: "não classificado",
      columnMenuSortAsc: "Classificar por ordem crescente",
      columnMenuSortDesc: "Classificar por ordem decrescente",
      columnMenuFilter: "Filtro",
      columnMenuHideColumn: "Ocultar",
      columnMenuShowColumns: "Mostrar colunas"
    };
    
    export default function DataTable({ rows, columns }) {
      const [finalClickInfo, setFinalClickInfo] = useState(null);
    
      const handleOnCellClick = (params) => {
        setFinalClickInfo(params);
      };
    
      return (
        <div style={{ height: 400, width: "100%" }}>
          <DataGrid
            rows={rows}
            columns={columns}
            pageSize={5}
            rowsPerPageOptions={[5]}
            checkboxSelection
            onCellClick={handleOnCellClick}
            localeText={localizedTextsMap}
          />
          {finalClickInfo &&
            `Final clicked id = ${finalClickInfo.id}, 
            Final clicked field = ${finalClickInfo.field}, 
            Final clicked value = ${finalClickInfo.value}`}
          {!finalClickInfo && `Click on a column`}
        </div>
      );
    }
    

    All the keys that can be localized are listed here. You can take a look at this stackblitz for a live working example of this usage.