0

On click of a button I open a dropdown where I want to shift the focus to the dropdown from the button. I need to access the dom element to do this. I read about ref and how to use it but it does not work.

constructor(){
   this.changeFocus = this.changeFocus.bind(this)
}
changeFocus() {
   this.test1.focus();
}
render(){
      let menu = (
                <Menu>
                    <MenuItem ref={(input) => { this.test1 = input; }} label="Test1"/>
                    <MenuItem ref={(input) => { this.test2 = input; }} label="Test2"/>
                </Menu>
                );
      return (
        <i onClick={this.changeFocus}</i>
        {menu} 
      )
}

But I get undefined. what is the correct way to get the dom element ?Please assume that changeFocus toggles the menu dropdown ie when user clicks on the icon it open the dropdown but focus remains on icon. I want it to go on the dropdown items

ksernow
  • 662
  • 3
  • 14
  • 33

2 Answers2

0

Assuming you are using Material UI, you can use the onMenuItemFocusChange property on your <Menu> and use the focusState property on the <MenuItem> you want to focus.

Store that value in the state or try to just set the focusState for the first item and see if that fits your use case.

http://www.material-ui.com/#/components/menu

klugjo
  • 19,422
  • 8
  • 57
  • 75
0

You are generating a new function and supplying it as the ref-callback. React has no way of knowing that it's (for all intents and purposes) identical to the previous one so React treats the new ref callback as different from the previous one and initializes it with the current reference. you should try setting pass in a callback function into the ref prop.

constructor(){
   this.changeFocus = this.changeFocus.bind(this)
}
changeFocus() {
   this.test1.focus();
}
setRef1 = ref => this.ref1 = ref
setRef2 = ref => this.ref2 = ref
render(){
      let menu = (
                <Menu>
                    <MenuItem ref={this.setRef1} label="Test1"/>
                    <MenuItem ref={this.setRef2} label="Test2"/>
                </Menu>
                );
      return (
        <i onClick={this.changeFocus}</i>
        {menu} 
      )
}
sxzhao
  • 116
  • 1