How to detect whether input element is focused within ReactJS?

Posted by Jessica Taylor | Updated on

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:

You will have to add a reference to the input element:

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:

Then set states in the handlers and check that state in the render method.

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.

Related Questions & Answers