0

I want to add the ability to search by clicking ENTER key. How can I add that in my code? This is from a codecademy project

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

class SearchBar extends Component {
    constructor(props) {
        super(props);
        this.search = this.search.bind(this);
        this.handleTermChange = this.handleTermChange.bind(this);
      }

      handleTermChange(event) {
        const newTerm = event.target.value;
        this.setState = ({ term: newTerm});
      }

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

    render() {
        return(
        <div className="SearchBar">
            <input placeholder="Enter A Song, Album, or Artist" onChange = {this.handleTermChange}/>
            <a onClick ={this.search}>SEARCH</a>
        </div>
        )}
}

export default SearchBar;

1 Answers1

4

React implements the onKeyUp method for inputs

 <input placeholder="Enter A Song, Album, or Artist" onChange={this.handleTermChange} onKeyUp={this.handleKeyPress.bind(this)}/>

And create a method in your component:

handleKeyPress(e) {
    if (e.key === 'Enter') {
        this.search(); 
    }
}
Raul Rene
  • 10,014
  • 9
  • 53
  • 75