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?
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}`;
}
}