Kalle Richter
Kalle Richter

Reputation: 8728

How to get the simplest Material UI Select to work with React and Typescript?

I'm trying to get the simplest Material UI Select to work in React with Typescript. I spend three hours on searching for an example which shows how to set the label or placeholder (I checked all properties of the API and those are the only ones that make sense).

There's simply no demo, example, tutorial, howto, article, documentation page that puts together look and code. A billion pages with mostly extremely complex code examples, but code only. And a billion pages with demos and image. Your chance to create the first useful explanation how to use Material UI Select!

The situation is simple: My code is

import React from "react"
import ReactDOM from "react-dom"
import MuiSelect from '@material-ui/core/Select'
import MuiMenuItem from '@material-ui/core/MenuItem'

class MyComponent extends React.Component<any, MyComponentState> {

  constructor(props: any) {
    super(props);
    this.state = {selectedAge: ""}
  }

  render() {
    return <div className="container">
      <MuiSelect id="offerType" label="Age" placeholder="Age" variant="outlined" value={this.state.selectedAge}>
        <MuiMenuItem value="1"/>
      </MuiSelect>
    </div>
  }
}

type MyComponentState = {
  selectedAge: string;
}

ReactDOM.render(
  <MyComponent/>,
  document.getElementById("root")
)

The expected output is an of these

enter image description here

from https://material-ui.com/components/selects/

And the current output is

enter image description here

Upvotes: 1

Views: 1946

Answers (1)

richbai90
richbai90

Reputation: 5204

As simple as I could make it

import React from "react";
import MuiSelect from "@material-ui/core/Select";
import MuiMenuItem from "@material-ui/core/MenuItem";
import InputLabel from "@material-ui/core/InputLabel";
import { FormControl } from "@material-ui/core";


class MyComponent extends React.Component<any, MyComponentState> {
  constructor(props: any) {
    super(props);
    this.state = { selectedAge: "" };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(evt: React.ChangeEvent<HTMLSelectElement>) {
    this.setState({ selectedAge: evt.target.value });
  }

  render() {
    return (
      <FormControl>
        <InputLabel id="age">Age</InputLabel>
        <MuiSelect
          onChange={this.handleChange}
          labelId="age"
          value={this.state.selectedAge}
          style={{width: '13em'}}
        >
          <MuiMenuItem value="1">1</MuiMenuItem>
          <MuiMenuItem value="2">2</MuiMenuItem>
        </MuiSelect>
      </FormControl>
    );
  }
}

type MyComponentState = {
  selectedAge: string;
};

You can check it out on codesandbox

Upvotes: 1

Related Questions