If you want to detect whether input element is focused within ReactJS? You can run something like this anytime as long as the input node is mounted and there is a reference to it:
1 2 3 | const ReactDOM = require('react-dom') if ( document.activeElement === ReactDOM.findDOMNode(this.refs.searchInput) ) |
You will have to add a reference to the input element:
1 | <input ref="searchInput" ... |
You should not do this in the render method though, because the input node might not be mounted yet. Use a lifecycle method like componentDidUpdate or componentDidMount.
Another way would be to add event listeners for the focus and blur events inside the input field:
1 | <input type="text" onFocus={this.onFocus} onBlur={this.onBlur}... |
Then set states in the handlers and check that state in the render method.
1 2 3 4 5 6 7 8 9 10 11 12 | onBlur: function() { this.setState({ focused: false }) }, onFocus: function() { this.setState({ focused: true }) }, render: function() { if ( this.state.focused ) { // do something } <input onFocus={this.onFocus} onBlur={this.onBlur}... } |
Note that this will call a re-render each time the node is focused or blurred (but this is what you want, right?)
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.