My MUI select not working with my array data with map function in react js

Viewed 25

I have this simple Select in which i am trying to show the data from the array.

but it shows empty select

In the console it shows the data but in select it won't show.

[webpack-dev-server] Server started: Hot Module Replacement enabled, Live Reloading enabled, Progress disabled, Overlay enabled.
Write.jsx:105 data 1
Write.jsx:105 data2 
Write.jsx:105 data3

let categories = ["data 1", "data2 ", "data3"];

<FormControl sx={{ minWidth: 120 }}>
            <InputLabel id="demo-simple-select-helper-label">
              Category
            </InputLabel>
            <Select
              labelId="demo-simple-select-helper-label"
              id="demo-simple-select-helper"
              value=""
              label="Category"
              onChange={handleCategoryChange}>
              {/* <MenuItem value="">
                <em>None</em>
              </MenuItem> */}
              {categories.map((key, value) => {
                console.log(value);
                <MenuItem key={key} value={value}>
                  {value}
                </MenuItem>;
              })}
            </Select>
          </FormControl>

2 Answers

Array.prototype.map() has the following syntax:

map((element) => { /* … */ })
map((element, index) => { /* … */ })
map((element, index, array) => { /* … */ })

When you write categories.map((key, value). The key is the string name of the category and value is actually the index.

Maybe try this:

{categories.map((s, index) => (
    <MenuItem key={index} value={s}>
      {s}
    </MenuItem>
))}

And also, the arrow syntax for the function works like this for returning the element: (s, index) => (<Element>...</Element>). When you write {} you need a return.

Working sandox here: https://codesandbox.io/s/stackoverflow-73743681-d3t4dr

You need to add the return and change the order of the paramaters you pass like this: value, key

{categories.map((value, key) => {
    console.log(value);
    return (
      <MenuItem key={key} value={value}>
            {value}
      </MenuItem>
    );
 })}`

and if you don't want the console.log(), you can return it directly like this:

{categories.map((value, key) => (
     <MenuItem key={key} value={value}>
         {value}
     </MenuItem>
))}
Related