olefrank
olefrank

Reputation: 6810

how to set fixed width of material-ui table cell to truncate content

I display a Table of users setup with infinite scroll. The first column contains the user name which varies in length. This makes the table jump in size as the list expands when scrolling down for more users. So I want to set a fixed width on that column and truncate the name column accordingly.

I tried to do it like but it doesn't work. The table cell adjust to the other cells and distributing the page width.

<Table>
    <TableBody>
        <TableRow>
            <TableCell style={{ width: '20%' }}>
                <Typography noWrap>SomeveeeeeeeeeeeeeryLoooooooooongNaaaaaame</Typography>
            </TableCell>
        </TableRow>
    </TableBody>
</Table>

How do I achieve this?

Upvotes: 1

Views: 5166

Answers (1)

bertdida
bertdida

Reputation: 5288

Create an ellipsis style and use that on your Typography component.

import { makeStyles } from '@material-ui/core/styles';

const useStyles = makeStyles({
  ellipsis: {
    maxWidth: 200, // percentage also works
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  },
});
...
const classes = useStyles();

<Table>
    <TableBody>
        <TableRow>
            <TableCell>
                <Typography className={classes.ellipsis}>
                    SomeveeeeeeeeeeeeeryLoooooooooongNaaaaaame
                </Typography>
            </TableCell>
        </TableRow>
    </TableBody>
</Table>

codesandbox

Upvotes: 7

Related Questions