Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manually lose focus from TextField select component, Material UI & React

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

like image 448
Sakhro Avatar asked Aug 16 '18 15:08

Sakhro


1 Answers

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.

like image 99
Kamen Stoykov Avatar answered Oct 24 '22 06:10

Kamen Stoykov