Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to focus a react-router Link

I have an input box used for searching, and want to be able to press the down key to move focus from the input to the first of a list of <Link>s. It seems what I have here won't work, since <Link> isn't an actual DOM node. I am able to get it to work using <a> instead of <Link> though.

let Link = require('react-router').Link

let SearchAndSelect = React.createClass({
  handleKeyPress: function (e) {
    if (e.keyCode === 40) { //'down' key
      this.refs['searchBox'].blur()
      this.refs['link0'].focus()
    }
  },

  render: function () {
    let ids = ['1', '2' , '3']

    return (
      <div>
        <input onKeyDown={this.handleKeyPress} ref="searchBox"/>

        <div>
          {ids.map((id, key) => (
            <Link to={`thing/${id}`}
              ref={`link${key}`}>
              {id}
            </Link>        
          ))}
        </div>
      </div>
    )
  }
})

Is there a way to use focus() with a react-router <Link>?

like image 745
chevin99 Avatar asked Mar 14 '26 01:03

chevin99


1 Answers

If you use ReactDOM.findDOMNode(this.refs['link0']).focus() it should work.

like image 160
Robin Venneman Avatar answered Mar 16 '26 17:03

Robin Venneman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!