Home > Mobile >  Material-Table is ignoring \n separators in data
Material-Table is ignoring \n separators in data

Time:10-22

I have a field in my Material-Table which contains a very long string. The string contains \n separators but the table is just ignoring these.

I have tried using \n\n, \r, \r\n, \n\r. None of these have worked.

Here is a quick example of the the field:

"Domain: Corporate, DomainLeader: John Doe,\n Experience: Finance,\n ExperienceLeader: Jane Doe,\n ProductLine: Finance Systems,\n ProductLineLeader: John Doe"

CodePudding user response:

You can use white-space: pre-wrap; style for this. I have made an example for you to understand it.

Example Code

import * as React from "react";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";

const rows = [
  {
    id: 1,
    text:
      "Domain: Corporate, DomainLeader: John Doe,\n Experience: Finance,\n ExperienceLeader: Jane Doe,\n ProductLine: Finance Systems,\n ProductLineLeader: John Doe"
  }
];

export default function BasicTable() {
  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} aria-label="simple table">
        <TableHead>
          <TableRow>
            <TableCell>Id</TableCell>
            <TableCell>Text</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {rows.map((row) => (
            <TableRow
              key={row.id}
              sx={{ "&:last-child td, &:last-child th": { border: 0 } }}
            >
              <TableCell>{row.id}</TableCell>
              <TableCell
                align="right"
                sx={{
                  whiteSpace: "pre-wrap"
                }}
              >
                {row.text}
              </TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </TableContainer>
  );
}

Result

enter image description here

CodePudding user response:

Setting render instructions onto the column to add a <br> after each comma has solved this issue for me

{
            title: <Typography className={classes.colHeader}>Taxonomy</Typography>,
            field: "Taxonomy",
            cellStyle: { minWidth: 400, maxWidth: 400 },
            render: (rowData) => (
                <Box style={{ flexDirection: "row" }}>
                    {rowData.Taxonomy.split(", ").map((b) => (
                        <Box style={{ display: "flex" }}>
                            <Box style={{ fontWeight: "bold" }}>{b.split(":")[0]}:</Box>
                            <Box>&nbsp;{b.split(":")[1]},</Box>
                        </Box>
                    ))}
                </Box>
            ),
        },
  • Related