LXT
LXT

Reputation: 845

Table Numbering in ReactJS

I am coding a table with ReactJS and MUI, I want to mark the No. column from 1 to the length of the array.

This is my code:

<TableBody>
    {quizes.map((quiz) => (
      <TableRow key={quiz._id}>
        <TableCell className={s.tablecell}>{.........}</TableCell>
        <TableCell className={s.tablecell}>
          {quiz.text}
        </TableCell>
        <TableCell className={s.tablecell}>
          {quiz.answer}
        </TableCell>
        <TableCell className={s.tablecell}>
          <Button
            size="small"
            variant="outlined"
            disableElevation
            color="info"
            className={s.btn}
            onClick={nevigateUpdateQuestion}
          >
            Edit
          </Button>
          <Button
            size="small"
            variant="outlined"
            disableElevation
            color="warning"
          >
            Delete
          </Button>
        </TableCell>
      </TableRow>
    ))}
</TableBody>

I use NodeJS and MongoDB as server so I cannot use quiz._id to number the table. How can I do to mark from 1 to the length of the array? The No. cell is in {.........} section.

Upvotes: 1

Views: 599

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13245

The second parameter of the map function is the index (0-based) of the iterating item. You can add one (index + 1) to get the 1-based number.

Try this

<TableBody>
    {quizes.map((quiz, quizIndex) => (
        <TableRow key={quiz._id}>
            <TableCell className={s.tablecell}>{quizIndex + 1}</TableCell>
            <TableCell className={s.tablecell}>{quiz.text}</TableCell>
            <TableCell className={s.tablecell}>{quiz.answer}</TableCell>
            <TableCell className={s.tablecell}>
                <Button
                    size="small"
                    variant="outlined"
                    disableElevation
                    color="info"
                    className={s.btn}
                    onClick={nevigateUpdateQuestion}
                >
                    Edit
                </Button>
                <Button
                    size="small"
                    variant="outlined"
                    disableElevation
                    color="warning"
                >
                    Delete
                </Button>
            </TableCell>
        </TableRow>
    ))}
</TableBody>

Upvotes: 1

Related Questions