Search code examples
javascriptreactjsmaterial-uimui-datatable

How can I expand the row only when that row was clicked?


I have this materia-ui table. Every time I'll click the button to expand the row1, it will also expand the second row. How can I fix this where only that specific row will expand?

<Table stickyHeader aria-label="sticky table">
  <TableHead>
    <TableRow hover>
      <TableCell>Title</TableCell>
      <TableCell>Created Date</TableCell>
    </TableRow>
  </TableHead>
  <TableBody>
  {data &&
   data((index) => (
    <TableRow hover>
      <TableCell>
        <IconButton
          aria-label="expand row"
          size="small"
          onClick={() => setOpen(!open)}
          >
          {open ? (
            <KeyboardArrowUpIcon />
          ) : (
            <KeyboardArrowDownIcon />
          )}
          </IconButton>
        </TableCell>
        <TableCell component="th" scope="row">
          {index.title}
        </TableCell>
        <TableCell component="th" scope="row">
          {new Date(
            index.createdDate.seconds * 1000
          ).toDateString()}
        </TableCell>
        <TableCell colSpan={6}>
          <Collapse in={open} timeout="auto" unmountOnExit>
            {index.text}
          </Collapse>
        </TableCell>
      </TableRow>
     ))}
   </TableBody>
 </Table>

Solution

  • Wrap TableRow in a component

    const Row = ({item}) => {
      const [open, setOpen] = useState(false);
    
      return <TableRow>...</TableRow>
    }
    
    <TableBody>
      {data.map((item, index) => (
        <Row key={index} item={item} />
      ))}
    </TableBody>
    

    Edit table-collapse