0

I created this web app http://jamwithme.surge.sh/ using Spotify API and I would like to implement a onEnterPress feature so the user can press enter to search tracks. But don't know where to begin.

import React, { Component } from "react";
import "./SearchBar.css";


// Search Bar for users to search tracks on spotify
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.search = this.search.bind(this);
this.handleTermChange = this.handleTermChange.bind(this);
this.onKeyPressHandler = this.onKeyPressHandler.bind(this);
}

onKeyPressHandler(event) {
if (event.keyCode === 13) {
  this.props.onSearch(this.state.term);
 }
 }

 search() {
 this.props.onSearch(this.state.term);
 }

 handleTermChange(event) {
 this.setState({term: event.target.value});
 }
 render() {
 return (
  <div className="SearchBar">
    <input placeholder="Enter a Song, Album, or Artist" 
    onChange={this.handleTermChange}
    onKeyDown={this.onKeyPressHandler}
    />
    <a onClick={this.search} >Search</a>
     </div>);}}

export default SearchBar;

Here my code it works now but is there any way to improve it?

Harman Pannu
  • 25
  • 11

2 Answers2

3

Just listen for the onKeyPress event and check for the event's keycode to be 13 (Enter key).

constructor(props) {
  super(props);
  this.onKeyPressHandler = this.onKeypressHandler.bind(this); // if you want to use `this` in the handler (maybe set a state or something)
}

onKeyPressHandler(event) {
  if (event.keyCode === 13) {
    // do something here [enter pressed]
  }
}

render() {
  return <input type="text" onKeyPress={this.onKeyPressHandler}> // search bar
}
Dangling Cruze
  • 3,283
  • 3
  • 32
  • 43
0

By default enter used with focusing. So when user is focused on some element enter will activate it, you can just use tab index to focus user on search button by default. Also you can just add an event listener to some component and check event’s key code — if it’s enter then do search.

Dmitriy Kovalenko
  • 3,437
  • 3
  • 19
  • 39