Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
72
rated 0 times [  78] [ 6]  / answers: 1 / hits: 160633  / 9 Years ago, wed, june 3, 2015, 12:00:00

How can I detect whether an input element such as the following is currently focused within a ReactJS render function?



<input type=text style={searchBoxStyle} placeholder=Search></input>   

More From » node.js

 Answers
4

You can check against document.activeElement as long as the input node is mounted and there is a reference to it:


const searchInput = React.useRef(null)

if (document.activeElement === searchInput.current) {
// do something
}

return <input type="text" ref={searchInput} />

Another way would be to add event listeners for the focus and blur events inside the input field:


const [focused, setFocused] = React.useState(false)
const onFocus = () => setFocused(true)
const onBlur = () => setFocused(false)

return <input type="text" onFocus={onFocus} onBlur={onBlur} />

Note that this will call a re-render each time the node is focused or blurred (but this is what you want, right?)


[#66352] Monday, June 1, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
;