Search code examples
reactjstypescriptmaterial-uimui-x-data-gridmui-x

With Material-UI's DataGrid component, how do I create multi layered text in one of the cells?


I'm trying to have two separate lines of text within one cell, where one line of text is on top of the other, in Material-UI's datagrid component and can not seem to get anything to work. This is what I have tried:

 const columns: ColDef[] = [
        {
            field: "name",
            headerName: "Sector",
            width: 300,
            renderCell: (params) => {
                let name = params.data.name
                const flow = params.data as IOFlow;
                const title = Currency.format(flow.value)
                    + " " + props.direction
                    + " per " + Currency.format(1);
                return (
                    <>
                         <Typography fullWidth display='block'>
                              {name}
                         </Typography>
                         <br/>
                         <Typography fullWidth display='block'>
                              {title}
                         </Typography>
                    </>
                );
            }
        },
    ];

Please let me know if there is anymore information I should provide.


Solution

  • The main issue is that you should not use a fragment (<>...</>) around your cell contents. Use a <div> instead. The cell is styled with display: flex which will layout the direct children (i.e. your Typography elements) horizontally. If you wrap the cell contents in a <div>, the contents within the <div> will behave as you would expect.

    Here's a working example:

    import * as React from "react";
    import { DataGrid } from "@material-ui/data-grid";
    import Typography from "@material-ui/core/Typography";
    
    const columns = [
      {
        field: "name",
        headerName: "Sector",
        width: 300,
        renderCell: (params) => (
          <div>
            <Typography>{params.value.name}</Typography>
            <Typography color="textSecondary">{params.value.title}</Typography>
          </div>
        )
      }
    ];
    
    const rows = [
      {
        id: 1,
        name: { name: "Name1", title: "Title1" }
      },
      {
        id: 2,
        name: { name: "Name2", title: "Title2" }
      },
      {
        id: 3,
        name: { name: "Name3", title: "Title3" }
      }
    ];
    
    export default function RenderCellGrid() {
      return (
        <div style={{ height: 300, width: "300" }}>
          <DataGrid rows={rows} columns={columns} />
        </div>
      );
    }
    

    Edit Multi-line DataGrid cell