Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a 'Select' component as required in Material UI (React JS)

I want to display like an error with red color unless there is a selected option. Is there any way to do it.

like image 785
Kusal Kithmal Avatar asked Jul 31 '18 04:07

Kusal Kithmal


People also ask

How do you get the selected value in autocomplete material UI?

To get the value in the React Material-UI autocomplete, we can get the selected values from the onChange callback. We add the Autocomplete from the @material-ui/lab module. And we set the options prop to the top5films array to add the options for the autocomplete.

How do you make a TextField mandatory in material UI?

We can use TextField component in Material UI to show input textbox. import TextField from "@material-ui/core/TextField"; When using the TextField component, we can pass the required attribute to mark the component as required.


2 Answers

For setting a required Select field with Material UI, you can do:

class SimpleSelect extends React.PureComponent {
  state = {
    selected: null,
    hasError: false
  }

  handleChange(value) {
    this.setState({ selected: value });
  }

  handleClick() {
    this.setState(state => ({ hasError: !state.selected }));
  }

  render() {
    const { classes } = this.props;
    const { selected, hasError } = this.state;

    return (
      <form className={classes.root} autoComplete="off">
        <FormControl className={classes.formControl} error={hasError}>
          <InputLabel htmlFor="name">
            Name
          </InputLabel>
          <Select
            name="name"
            value={selected}
            onChange={event => this.handleChange(event.target.value)}
            input={<Input id="name" />}
          >
            <MenuItem value="hai">Hai</MenuItem>
            <MenuItem value="olivier">Olivier</MenuItem>
            <MenuItem value="kevin">Kevin</MenuItem>
          </Select>
          {hasError && <FormHelperText>This is required!</FormHelperText>}
        </FormControl>
        <button type="button" onClick={() => this.handleClick()}>
          Submit
        </button>
      </form>
    );
  }
}

Working Demo on CodeSandBox

Edit soanswer51605798

like image 143
Jee Mok Avatar answered Oct 05 '22 22:10

Jee Mok


Material UI has other types of Select(native) also where you can just use plain HTML required attribute to mark the element as required.

<FormControl className={classes.formControl} required>
  <InputLabel htmlFor="name">Name</InputLabel>
  <Select
    native
    required
    value={this.state.name}
    onChange={this.handleChange}
    inputProps={{
      name: 'name',
      id: 'name'
    }}
  >
    <option value="" />
    <option value={"lala"}>lala</option>
    <option value={"lolo"}>lolo</option>
  </Select>
</FormControl>

P.S. https://material-ui.com/demos/selects/#native-select

like image 37
Novice_JS Avatar answered Oct 05 '22 23:10

Novice_JS