0

The dropdown show the value from database, but when I select it the value is undefined.

import {
    Select,
    MenuItem,
    FormControl,
    InputLabel,
  } from "@material-ui/core"; 

function FilePush() {
const [categorias, setCategorias] = useState([]);
const [fileID, setFileID] = useState("");

    return (
        <Container component="main" maxWidth="xs">
        <Select onChange={(e) => setFileID(e.target.value)}>
        <MenuItem value="None">
          <em>None</em>
        </MenuItem>

        {categorias.map((categoria,index ) => {
        return (
          <div key={index}>

            {categoria.json.map((f) => {
              return (
                <div key={f.filename}>

                   <MenuItem key={f.filename} value={f.filename} >{f.filename}</MenuItem>
                </div>
              );
            })}

            <hr />
          </div>
        );
      })}
         </Select>
        
         <p>You Selected: {fileID}</p>

    )
}
}

export default FilePush;

The code shows values that are coming from Database in the dropdown. However, when the options are selected, the result is undefined.

1 Answer 1

1

The <div> within the <Select> element seems to be the problem. In other words, the <MenuItem> needs to be placed directly below the <Select> element.

In your case, there are 2 <div> elements under <Select>. Can you try removing it and see if it works?

I have confirmed the behavior with the below code sandbox. Adding <div> create the issue and no <div> works fine. (The code is forked from the MUI <Select> documentation.) https://codesandbox.io/s/amazing-sinoussi-4ow5ig?file=/demo.js


{ 
  categorias.map((categoria) => {
    categoria.json.map((f) => {
      return (
        <MenuItem key={f.filename} value={f.filename} >{f.filename}</MenuItem>
      )
    });
  });
}
Sign up to request clarification or add additional context in comments.

3 Comments

I'm getting the data from psql, and I need to loop the data twice. If I want to delete the div, then I have to delete the return. If I delete the return and div, I will have an empty dropdown.
@HaniMoghaddasi How about returning only <MenuItem>? The sample code was added to the answer.
It makes the dropdown empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.