Ask Your Question
0

What is the process for choosing several dropdown options and displaying them as a string separated by commas in a React material table?

asked 2023-05-05 00:50:15 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-05 01:13:02 +0000

lalupa gravatar image
  1. Create an array state variable to store the selected options.
  2. Add a dropdown component to the table column using the Material-UI Select component.
  3. Use the useState hook to update the array state variable whenever an option is selected or deselected.
  4. Add an event listener to the dropdown component that updates the array state variable.
  5. Define a function that takes the array state variable as input and returns a string of the selected options separated by commas.
  6. Display the string returned by the function in the table cell using the Material-UI Typography component.

Here is an example of what the code might look like:

import React, { useState } from 'react';
import { Table, TableBody, TableCell, TableHead, TableRow, Typography, Select, MenuItem } from '@material-ui/core';

const options = ['Option 1', 'Option 2', 'Option 3'];

function App() {
  const [selectedOptions, setSelectedOptions] = useState([]);

  const handleChange = (event) => {
    const selected = event.target.value;
    setSelectedOptions((prevSelected) => {
      if (prevSelected.includes(selected)) {
        return prevSelected.filter((option) => option !== selected);
      } else {
        return [...prevSelected, selected];
      }
    });
  };

  const formatOptions = (optionsArray) => {
    return optionsArray.join(', ');
  };

  return (
    <Table>
      <TableHead>
        <TableRow>
          <TableCell>Selected Options</TableCell>
        </TableRow>
      </TableHead>
      <TableBody>
        <TableRow>
          <TableCell>
            <Select multiple value={selectedOptions} onChange={handleChange}>
              {options.map((option) => (
                <MenuItem key={option} value={option}>
                  {option}
                </MenuItem>
              ))}
            </Select>
          </TableCell>
        </TableRow>
        <TableRow>
          <TableCell>
            <Typography>{formatOptions(selectedOptions)}</Typography>
          </TableCell>
        </TableRow>
      </TableBody>
    </Table>
  );
}

export default App;
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-05 00:50:15 +0000

Seen: 8 times

Last updated: May 05 '23