Search code examples
javascriptreactjsmaterial-uidropdown

React - Material UI table to contain a dropdown in each row


so I have this Table I've rendered its rows from an array map as shown below

<TableContainer component={Paper}>
            <Table className={classes.table} aria-label="simple table">
              <TableHead>
                <TableRow>
                  <TableCell>Object Name</TableCell>
                  <TableCell align="center">Object Field and Values</TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {union &&
                  unionArray.map((row) => (
                    <TableRow key={row.name}>
                      <TableCell component="th" scope="row">
                        {row.name}
                      </TableCell>
                      {Object.keys(row).map((key) =>
                        key === "name" ? (
                          ""
                        ) : (
                          <TableCell align="center">
                            {/*insert dropdown select*/}
                            <FormControl
                              variant="outlined"
                              className={classes.formControl}
                            >
                              <InputLabel htmlFor="outlined-age-native-simple">
                                Values
                              </InputLabel>
                              <Select
                                native
                                label="Value"                                
                              >
                                <option aria-label="None" value="" />
                                <option>{key}:{row[key]}</option>                                
                              </Select>
                            </FormControl>
                          </TableCell>
                        )
                      )}
                    </TableRow>
                  ))}
              </TableBody>
            </Table>
          </TableContainer>

the array of objects where I mapped from is shown below. i.e UnionArray unionarray

my problem is the rows that have a third key/value pair are rendering as entire table cell, I just want them to be part of the dropdown. the output now is something like this output


Solution

  • I don't have enough reputations to comment but the answer lies in @lakshya's response and @ahmed's comment. Object.keys will return null for when key === 'name' but it will return valid JSX for when the keys aren't name, hence, your table cell having 2 dropdowns.

    As for how to go about formatting the response, you can format your loop like in the image attached.code of block for formatting response