title: A method to manage keyboard shortcuts in react
body: <p>Keyboard shortcuts are a bit tricky to manage in web applications. </p>
  
  <p>consider a <code>Widget</code> component.</p>
  
  <p>I want to be able to focus certain elements, and run functions on this component, based on keyboard shorcuts.</p>
  
  <pre><code>class Widget extends React.Component {
    componentDidMount() {
      this.setBindings()
    },
    componentWillUnmount() {
      this.removeBindings();
    }
  } 
  </code></pre>
  
  <p>setBindings and removeBindings, would use a library like <a href="https://craig.is/killing/mice" rel="noreferrer">mousetrap</a> to bind specific keyboard shortcuts</p>
  
  <p>Now, there's two problems with the above solution: </p>
  
  <ol>
  <li>It makes keyboard shortcut behavior unpredictable
  
  <ul>
  <li>Consider the case where two Widgets mount, one would override the other</li>
  </ul></li>
  <li>Widget becomes tightly coupled with the shortcuts -- now if someone doesn't want to use shortcuts, they have to have some sort of flag on <code>Widget</code>. This destroy's the 'granularity' of the code -- ideally a user should be able to use Widget, then WidgetWithShortcuts, or something like this</li>
  </ol>
  
  <p>Another potential solution, is to pass an instance </p>
  
  <pre><code>const widgetShortcuts = (widgetInstance) =&gt; {
    return {
     'ctrl i': () =&gt; widgetInstance.focusInput(),
    }
  }
  </code></pre>
  
  <p>The problem with the second solution is:</p>
  
  <ol>
  <li><p>widgetInstance will have to expose a lot of publicly accessible methods, like focusSomeThing, or invokeProp, etc</p></li>
  <li><p>if <code>Widget</code> wants to have some tooltip, that shows the keyboard shortcuts at certain places, the info about the keyboard shorcuts will be duplicated in different places. It will become possible to change the shortcuts in one place, and forget to do so in another places</p></li>
  </ol>
  
  <p>Is there a best practice, or some ideas on how keyboard shortcuts can be implemented with solutions to the problems above?</p>