material ui select not working when a list of data to be rendered

Viewed 3544

I am trying to display the select in material ui where I need to select one item of all the values we can select . Here is the code . I have datatoloop and I need to iterate over it and select the subjects and get their id in console .I could not figure out as what I did wrong or does material ui accepts only the format it is shown in docs page . Here is the docs page

docs link

Here is the link to sandbox where I tried editing the code sandbox link

    import React from "react";
    import PropTypes from "prop-types";
    import { withStyles } from "@material-ui/core/styles";
    import Input from "@material-ui/core/Input";
    import InputLabel from "@material-ui/core/InputLabel";
    import MenuItem from "@material-ui/core/MenuItem";
    import FormHelperText from "@material-ui/core/FormHelperText";
    import FormControl from "@material-ui/core/FormControl";
    import Select from "@material-ui/core/Select";

    const styles = theme => ({
      root: {
        display: "flex",
        flexWrap: "wrap"
      },
      formControl: {
        margin: theme.spacing.unit,
        minWidth: 120
      },
      selectEmpty: {
        marginTop: theme.spacing.unit * 2
      }
    });
    let datatoloop = [
      { id: 100, subject: "math" },
      { id: 101, subject: "physics" },
      { id: 102, subject: "chemistry" }
    ];
    class SimpleSelect extends React.Component {
      state = {
        age: "",
        name: "hai"
      };

      handleChange = event => {
        this.setState({ [event.target.name]: event.target.value });
      };

      render() {
        const { classes } = this.props;

        return (
          <form className={classes.root} autoComplete="off">
            <FormControl className={classes.formControl}>
              <InputLabel htmlFor="age-simple">Age</InputLabel>
              <Select
                value={this.state.age}
                onChange={this.handleChange}
                inputProps={{
                  name: "age",
                  id: "age-simple"
                }}
              >
                <MenuItem value="">
                  <em>None</em>
                </MenuItem>
                {datatoloop.map(item => {
                  <MenuItem value={item.id}>{item.subject}</MenuItem>;
                })}
              </Select>
            </FormControl>
          </form>
        );
      }
    }

    SimpleSelect.propTypes = {
      classes: PropTypes.object.isRequired
    };

    export default withStyles(styles)(SimpleSelect);
2 Answers

You forgot to return components while mapping them in your react tree.

here is the working codesandbox: MenuItems Rendering

return  <MenuItem value={item.id}>{item.subject}</MenuItem>;
Related