Ad

Set Focus On Input Element After Clicking An Anchor Tag In React

- 1 answer

I have two components:

In my parent component I have:

    //set focus object to false
    // include Child Component and React libraries
    const parent = React.createClass({
    getInitialState: function() {
      return {
        focus: false
      };
    },
      render() {
        return(
          <div>
            <Child focus={this.state.focus} />
            <a onClick={this._handleClick}>Click me</a>
          </div>
        );
      },

      _handleClick: function() {
        this.setState({focus: !this.state.focus});
      },
    };

And inside my Child component I have an input tag:

 const child = React.createClass({
      render() {
        return(
          <div>
            <input type="text" ref="input" />
          </div>
        );
      },

  componentWillReceiveProps: function() {
    this.refs.input.focus();
  },
};

In summary what I am trying to do in my method is to focus on the input tag by changing the prop to call componentWillReceiveProps. However right now this is not working. It ends up just focusing on the anchor tag. Any idea of what I am doing wrong?

Edit: To further go into detail about my issue is that once I click the anchor tag, the input element in the child component does not get focused on. How can i make it get focused on?

Ad

Answer

componentWillReceiveProps executes before the child's render method. So the render is likely clobbering the input element right after it has been given focus. Most likely you can just change componentWillReceiveProps to componentDidUpdate and you'll be good to go.

Ad
source: stackoverflow.com
Ad