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

别说谁变了你拦得住时间么 提交于 2020-01-12 07:32:07

问题


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


回答1:


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

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

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

  handleClick() {
    this.setState({ hasError: false });
    if (!this.state.selected) {
      this.setState({ hasError: true });
    }
  }

  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




回答2:


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



来源:https://stackoverflow.com/questions/51605481/how-to-make-a-select-component-as-required-in-material-ui-react-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!