title: Trigger a button's onClick on key press in React
body: <p>So basically I have a login page without a form and I want to trigger the login button's onClick when the user presses enter. </p>
  
  <p>I tried adding an event listener to the page like so:</p>
  
  <pre><code>componentWillMount() {
     const { handleKeyPress, username, password } = this.props;
     document.addEventListener('keydown', (event, username, password) =&gt; handleKeyPress(event.key));
  }
  </code></pre>
  
  <p>The problem is that that listener is instantiated when the component mounts which means that the props username and password are in their initial state (i.e. empty).</p>
  
  <p>Adding the event listener to componentWillReceiveProps doesn't work for similar reasons.</p>
  
  <p>Basically with this solution I'd need to not send username and password from the function in the event listener and instead fetch username and password from the state in mapDispatchToProps where the function in the event listener is defined, but that's a very ugly solition. </p>
  
  <p>What I was looking for in the beginning was to add a listener to the button similar to onClick and basically as such:</p>
  
  <pre><code>&lt;button
    onEnterKeyPress={() =&gt; handleLogin(this.props.username, this.propspassword)}
  &gt;
    Log in
  &lt;/button&gt;
  </code></pre>
  
  <p>But as far as I know there is no way of doing that... hopefully I'm wrong though! If anyone has some ideas, please share.</p>