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

1 Answer 1

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(); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.