Micheal J. Roberts
Micheal J. Roberts

Reputation: 4170

Reactjs: unfocusing a button element using .blur()

I'm having a little issue whilst learning react - I'd like to unfocus (a.k.a blur()) a button DOM element, but for some reason this isn't quite working.

I think the issue, from what I can read, is around the use of the reactstrap Button component:

<Button className={buttonClass} onClick={this.handleCopyToClipboardClick} ref={this.buttonBlurRef}>
  <div className="d-flex justify-content-between">
    <span></span>
    <span>{ this.state.hasCopiedToClipboard ? 'Copied to clipboard!' : this.state.buttonText }</span>
    <span><FontAwesomeIcon icon="copy" /></span>
  </div>
</Button>

I'm binding a ref on a component? I think this is why it's not working.

The onClick function is working, which I have included below. I've including some commented out code out of things I have tried - all of which break the handleCopyToClipboardClick function.

handleCopyToClipboardClick() {
  this.setState(state => ({
    hasCopiedToClipboard: !state.hasCopiedToClipboard
  }));

  // this.buttonBlurRef.current.blur(); <= This isn't working

  // this.buttonBlurRef.blur(); <= This isn't working either

  // this.refs.buttonBlurRef.current.blur(); <= Or this

  // this.refs.buttonBlurRef.blur(); <= Nor this... :'(

  setTimeout(
    function() {
      this.setState(state => ({
        hasCopiedToClipboard: !state.hasCopiedToClipboard
      }));
    }.bind(this),
    1500
  );
}

Here is my Component constructor as well:

constructor(props) {
  super(props);
  this.buttonBlurRef = React.createRef();

  this.state = {
    hasCopiedToClipboard: false,
  };

  this.handleCopyToClipboardClick = this.handleCopyToClipboardClick.bind(this);
}

Any advise on how I could potentially unfocus my Bootstrap Button would be great! :)

Upvotes: 3

Views: 23309

Answers (2)

Sahil Arora
Sahil Arora

Reputation: 491

I read on Reactstrap website that,

ref will only get you a reference to the Button component, use innerRef to get a reference to the DOM element (for things like focus management).

So, just replace ref with innerRef on the Button Component.

https://reactstrap.github.io/components/buttons/

After getting reference of DOM element it can be blur by this.buttonBlurRef.blur().

Hope this helps,

Cheers !!

Upvotes: 3

Maciej Kwas
Maciej Kwas

Reputation: 6429

You have an activeElement property in your document, so you could probably just call document.activeElement.blur() and it should work. You can also try to go other way around and instead of calling blur on your element- call focus on some other, like whole document for example: window.focus() or document.body.focus(). Hope this helps

Upvotes: 15

Related Questions