Is it possible to focus a div (or any other elements) using the focus() method?
I set tabIndex to the div element:
<div ref="dropdown" tabIndex="1"></div>
And I see that it focuses when I click on it, however I am trying to dynamically focus the element as follows:
setActive(state) { ReactDOM.findDOMNode(this.refs.dropdown).focus(); }
Or like this:
this.refs.dropdown.focus();
But the component does not receive focus when the event fires. How can i do this? Is there any other (non-input) element that I can use for this?
EDIT:
Well, it seems like it really can be done: https://jsfiddle.net/69z2wepo/54201/
But this does not work for me, this is my complete code:
class ColorPicker extends React.Component { constructor(props) { super(props); this.state = { active: false, value: "" }; } selectItem(color) { this.setState({ value: color, active: false }); } setActive(state) { this.setState({ active: state }); this.refs.dropdown.focus(); } render() { const { colors, styles, inputName } = this.props; const pickerClasses = classNames('colorpicker-dropdown', { 'active': this.state.active }); const colorFields = colors.map((color, index) => { const colorClasses = classNames('colorpicker-item', [`colorpicker-item-${color}`]); return ( <div onClick={() => { this.selectItem(color) }} key={index} className="colorpicker-item-container"> <div className={colorClasses}></div> </div> ); }); return ( <div className="colorpicker"> <input type="text" className={styles} name={inputName} ref="component" value={this.state.value} onFocus={() => { this.setActive(true) }} /> <div onBlur={() => this.setActive(false) } onFocus={() => console.log('focus')} tabIndex="1" ref="dropdown" className={pickerClasses}> {colorFields} </div> </div> ); } }
source share