8
votes

I have a select input which I create by using TextField component from Material-UI lib. I need to manually lose focus after some option been selected. I tried to use a reference to the TextField using 'inputRef' prop, which works great but when I try to fire blur() function on this.selectInput.current like I did here but without MaterialUI lib.

class Select extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    	selected: ''
    }
    
    this.inputRef = React.createRef();
    this.onChangeHandler = this.onChangeHandler.bind(this)
  }
  
  onChangeHandler(e){
  
	this.inputRef.current.blur()

  	this.setState({
    	selected: e.target.value
    })
  }
  
  render() {
  	const {selected} = this.state;
  
    return (
      <select value={selected}
          onChange={this.onChangeHandler}
          ref={this.inputRef}>
        <option value=''>Please select</option>
        <option value='1'>One</option>
        <option value='2'>Two</option>
      </select>
    )
  }
}

ReactDOM.render(<Select />, document.querySelector("#app"))
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<div id="app"></div>

I got an error that blur() function does not exist. I understand that Material UI used custom el. to create UI and I target just a div or whatever. So the question is it another way to get the exact behavior (lose focus on the select event) when using TextField component or maybe I did something wrong?

Material UI v1.3.1 | React v16.4.2

2

2 Answers

4
votes

Try to define onClose method with the following body:

onClose() {
    setTimeout(() => {
        document.activeElement.blur();
    }, 0);
}

and then pass this method to onClose prop of the select element.

0
votes

I faced similar issue with blur event in react material-ui Select component

Below solution worked for me.

import Select from '@material-ui/core/Select';
<Select
...
onClose={()=>{
    setTimeout(() => {
        setOpen(false)
        handleSubmit();
    }, 0);
}}
/>