React Table with Grid

We will now implement a table for our data with Grid. We will create a StyledTable component to act as our grid. We're showing MissionsTable in the editor which will export the new table. Click on the Missions link in the browser to see the missions.

Let's review how to create a grid table. In StyledTableRow, we first declare display: grid. This turns our normal div into a CSS Grid. Awesome. Now, we have to declare the columns. We'll set a fixed 180px for the mission name, then let the description flow to available remaining space with 1fr, finally a fixed 80px for the date.

We'll ensure to vertically center the items with align-items: center, add some padding between rows, and set a height of 30px for each row. On hover, we'll set the background color to lightgray.

We also specify a TableCell to have text-overflow: ellipsis so the content doesn't run off the edge of the row. And the justify-right can be dynamically set so the last date column aligns to the far right of the table.

Menu
Lesson 18/26
import styled from "styled-components";

const StyledTable = styled.div`
  display: grid;
  gap: 8px;
  grid-auto-rows: min-content;
  min-height: 300px;
`;

const StyledTableRow = styled.div`
  display: grid;
  height: 30px;
  grid-template-columns: 180px 1fr 80px;
  cursor: pointer;
  align-items: center;
  padding: 4px;
  &:hover {
    background-color: lightgray;
  }
`;

const TableCell = styled.div`
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  ${({ justifyRight }) =>
    justifyRight &&
    `
    justify-self: right; 
  `}
`;

function MissionRow({ data: { id, title, description, created_at } }) {
  return (
    <StyledTableRow>
      <TableCell> {title} </TableCell>
      <TableCell> {description} </TableCell>
      <TableCell justifyRight> {created_at} </TableCell>
    </StyledTableRow>
  );
}

function MissionsTable({ missions }) {
  return (
    <StyledTable>
      {missions.map((data) => (
        <MissionRow key={data.title} data={data} />
      ))}
    </StyledTable>
  );
}

export default MissionsTable;