Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React unable to focus on div

Tags:

reactjs

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.

like image 352
Anis Smail Avatar asked Jul 31 '17 15:07

Anis Smail


1 Answers

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>
...
like image 156
Andrew Avatar answered Oct 23 '22 08:10

Andrew