Search code examples
javascriptinputreactjsfocusonblur

REACT -- How to change the click state of a focused / blurred event


I'm trying to switch between a focused / blurred state for a search bar. Right now the tag has a click handler that shows an input field if the element is clicked. I'm trying to reverse this effect and hide the visibility of the input field when the user clicks outside the element.

My code is:

var Search = React.createClass({

  getInitialState:function(){
    return{ inputVisible:false }
  },
  showInput:function(){
    this.setState({ inputVisible:true });
  },
  componentDidUpdate:function(){
    if( this.state.inputVisible ){
      this.getDOMNode().focus();
    }
  },
  renderInput: function(){
    return (  
      <input type="text" style={this.props} />
    );
  },
  renderLink: function(){
    return (
      <a><h3 onClick={this.showInput}>Search</h3></a>
    );
  },
  render: function() {
    if( this.state.inputVisible ){
      return this.renderInput();
    }else{
      return this.renderLink();
    }
  }
});

I've tried adding logic to the componentDidUpdate function, so that

if (input.state.isVisible == false ) {
    this.getDOMNode().blur();
}

I've also tried adding an onBlur handler to the element and tried creating a hideInput method:

hideInput: function() {
    this.setState({ inputVisible:false });
}

and adding to the element:

<a><h3 onClick={this.showInput} onBlur={this.hideInput}>Search</h3></a>

But something just isn't working. Can anyone point out what I'm doing wrong?


Solution

  • You can't focus an H3 element without a tabindex attribute, and so it can't be "blurred" to begin with, thus the onBlur event doesn't fire. Try attaching the onBlur event on the rendered input element in your renderInput method.

    Here's an example: http://plnkr.co/edit/STMPIkIQEIAZPZQ9SCq4?p=preview