2

I have been searching SO for a while so this should not be a duplicate. But, I am trying to trigger a link click when the enter key is pressed.

This is what I am working with:

handleKeyPress(target) {
  if(target.charCode==13){
    alert('Enter clicked!!!');    
  }
}

Search input:

<SearchBox
  type="text"
  value={value}
  onChange={e => this.onChange(e)}
  className="search-box"
  placeholder="Search"
  aria-label="search"
  aria-describedby="basic-addon2"
  onKeyPress={this.handleKeyPress}
/>
<div>
  <Link to={`/search?q=${value}`} className="btn submit-button"><i className="fa fa-search"></i></Link>
</div>

Using React Instant Search I want to submit the inputs 'value' when enter is clicked. Currently I can only submit the value when I physically click on:

<div>
  <Link to={`/search?q=${value}`} className="btn submit-button"><i className="fa fa-search"></i></Link>
</div>

I can get the link to fire. But, how can I get the same functionality as the link click when I press enter too? Any suggestions on how to link to the search value via KeyPress?

brooksrelyt
  • 3,925
  • 5
  • 31
  • 54

2 Answers2

3

If you already react-router-dom you can use the following:

import { withRouter } from 'react-router-dom'
class *ClassName* extends React.Component {
  ..
  handleKeyPress(target, value) {
    const { history } = this.props;
    if(target.charCode==13){
      history.push(`/search?q=${value}`);
    }
  }
  ..
  render() {
    return (
      ..
      <SearchBox
        value={value}
        ..
        onKeyPress={e => this.handleKeyPress(e, value)}
      />
    )
  }
  ..
}

export default withRouter(*ClassName*);

Important here ist that you use the withRouter(..) export to get the history from your props.

ChrKahl
  • 641
  • 5
  • 25
2

According to react-statics documentation they recommend installing Reach Router for dynamic routing. To navigate programmatically with Reach Router you should be able to import navigate.

import { navigate } from "@reach/router"

...

handleKeyPress(target) {
  // I'm guessing you have value stored in state
  const { value } = this.state;
  if(target.charCode==13){
    navigate(`/search?q=${value}`);
  }
}

Option 2

Honestly that seems like a lot of work when you could probably just do it with javascript.

handleKeyPress(target) {
  // I'm guessing you have value stored in state
  const { value } = this.state;
  if(target.charCode==13){
    const { href } = window.location;
    window.location.href = `${href}/search?q=${value}`;
  }
}
sallf
  • 2,583
  • 3
  • 19
  • 24