Add query to BooksSearch - KatyaHorton/Udacity-MyReads-PROJECT GitHub Wiki

  1. Add query property to our string
state = {
 query=''
}
  1. Update input field
  • value always has to be 'this.state.query'
  • when input field changes we want to update our query (create updateQuery function)
<input 
 type="text" 
 placeholder="Search by title or author"
 value={this.state.query}
 onChange={(event) => this.updateQuery(event.target.value)}
 />			
  1. Add function to update query when input field is a target of change:
  • updates query with setState()

updateQuery = (query) => {
this.setState({ query: query.trim() })
}
  1. To check if query is actually getting updated when smth is typed in the input use that code:
{JSON.stringify(this.state.query)}
  1. Install packages to update state to filter books:
npm install --save escape-string-regexp sort-by
  • restart application
  • import packages
 import escapeRegExp from 'escape-string-regexp' 
 import sortBy from 'sort-by'
  1. Create new variable which will display only books with fit the filter based on the state of query:
  let showBooks
  	if (this.state.query) {
		const match = new RegExp(escapeRegExp(this.state.query), 'i')
		showBooks = this.props.books.filter(
//search must match either book author or title
		(book) => match.test(book.title)
//if it does not match any of them, showBooks should be an empty string         									)
		} else {
			showBooks = []
		}