javascriptreactjstextareaeslint

How to add a keyboard listener to my onClick handler?


I have the following:

class MyTextArea extends React.Component {

  handleClick = () => {
    this.focus();
  }
    
  focus = () => this.ref.focus;

  handleRef = (component) => {
    this.ref = component;
  };

  render() {
    return (
      <div className="magicHelper" onClick={this.handleClick}>
        <textarea></textarea>
      </div>
    );
  }
}

My CSS:

.magicHelper {
  width: 100%;
  height: 100%;
}
textarea {
  line-height: 32px;
}

I need this because I need the textarea's placeholder to be horizontally and vertically centered in the page. Given textareas can't vertically center text, I need to keep the height of the textarea short. I therefore need to make it so that when the user clicks outside of the textarea, thinking they are clicking the textarea, the textarea auto focuses in.

This is causing an ESLint error:

"Visible, non-interactive elements with click handlers must have at least one keyboard listener".

How can I update the above to pass eslint?


Solution

  • https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/click-events-have-key-events.md

    It seems this rule is to enforce Accessibility standards.

    Based on this, change your code to do something like this

    <div className="magicHelper" onClick={this.handleClick} onKeyDown={this.handleClick}>
    

    You could also disable the rule in eslint, I suppose it depends on preference.