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

前端 未结 2 1772
伪装坚强ぢ
伪装坚强ぢ 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: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 (
          
    Name } > Hai Olivier Kevin {hasError && This is required!}
    ); } }

    Working Demo on CodeSandBox

提交回复
热议问题