Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly create a cmd+K keyboard shortcut in react?

I made a keydown/keyup script that fires a search bar when pressing cmd+k. The issue I'm facing is that the browser doesn't recognize when I'm holding the cmd key. For the "K" key, there's seem to be an autorepeat by default thus allowing me to simply hold "K" and pressing Cmd to show the search bar.

I want the reverse. How can I hold Cmd and press another key (K) to fire my search bar?

class Dashboard extends Component {
    
    state = {
        showSearch: "",
        HideShowSearch: false,
    };


HideShowSearch = (e) => {
        var map = {};
        let HideShowSearch = this.state.HideShowSearch;
        var self = this;
        onkeydown = function (e) {
            e = e;

            map[e.keyCode] = e.type === "keydown";

            // Cmd + K
            if (map[75] && map[91]) {
                self.setState(() => ({ HideShowSearch: !HideShowSearch }));
            }
        };
    };

render() {
        this.HideShowSearch();
        return (
            <div>
                <div className="row align-items-center">
                    <div className="container col-12">
                        {this.state.HideShowSearch ? (
                            <Searchbox
                                onChange={this.onTextChanged}
                                item={this.state.items}
                                onKeyPress={this.handleKeyPress}
                                text={this.state.text}
                                suggestions={this.renderSuggestions()}
                                onKeyDown={this.onKeyDown}
                            />
                        ) : null}
                    
                    </div>
                </div>
            </div>
        );
    }
like image 604
Dom355 Avatar asked Oct 27 '25 01:10

Dom355


1 Answers

e.keyCode === 75 && e.metaKey produces the described behavior in both directions (not quite reverse)

class Test extends React.Component {

  handleKeyDown = (e) => {
    if (e.keyCode === 75 && e.metaKey) {
      console.log("search")
    }
  };

  render() {
    return <input onKeyDown = {this.handleKeyDown}/>
  }

}

ReactDOM.render( < Test / > , document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
like image 190
Pavlos Karalis Avatar answered Oct 28 '25 15:10

Pavlos Karalis