I am trying to focus on a div when I click on a button like here. I reduced my problem to the code bellow, where although focus is called on the div object, onFocus is never called. Also autoFocus
doesn't solve my problem because I want to be able to change focus multiple time after the component did mount.
class App extends React.Component {
constructor() {
super();
this.my_refs = {};
this.focusByID.bind(this);
}
focusByID(id){
let myRef = this.my_refs[id];
if(myRef){
console.log('focusing on ', id, myRef);
myRef.focus();
}
}
render() {
return (
<div>
<div
id="bigRedDiv"
style={{height : 200, width : 200, backgroundColor : 'red'}}
ref={(input) => this.my_refs['bigRedDiv'] = input }
onFocus={() => console.log('FOCUS IS ON BIG RED DIV')}
onClick={() => this.focusByID('bigRedDiv')}
>
</div>
</div>
);
}
}
Here is a fiddle containing this code.
Just:
...
<div
tabIndex="0" //use this attribute
id="bigRedDiv"
style={{height : 200, width : 200, backgroundColor : 'red'}}
ref={(input)=> this.my_refs['bigRedDiv'] = input }
onFocus={() => console.log('FOCUS IS ON BIG RED DIV')}
onClick={() => this.focusByID('bigRedDiv')} >
</div>
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With