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

前端 未结 2 1770
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 12:53

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

相关标签:
2条回答
  • 2021-02-07 13:12

    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

    0 讨论(0)
  • 2021-02-07 13:21

    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

    0 讨论(0)
提交回复
热议问题