I am new to development and recently learned react. I am making an event hosting application and implementing a search bar but I'm running into an error when I type something in the search bar.
In the event.jsx file I have handleSearch function.
handleSearch = query => {
this.setState({ searchQuery: query });
};
getPagedData = () => {
const {
searchQuery,
events: allEvents
} = this.state;
let filtered = allEvents;
if (searchQuery)
filtered = allEvents.filter(e =>
e.title.toLowerCase().startsWith(searchQuery.toLowerCase())
);
return { totalCount: filtered.length };
};
this is my search bar component and it is saying that the onChange is not a function.
import React from "react";
const SearchBox = ({ value, onChange }) => {
return (
<div className="search-box">
<input
className="search-txt"
type="text"
name="query"
placeholder="search"
value={value}
onChange={e => onChange(e.currentTarget.value)}
/>
<a className="search-btn" href="">
<i className="fa fa-search" />
</a>
</div>
);
};
export default SearchBox;
this is what I have in my State-
class Events extends Component {
state = {
events: getEvents(),
showDetails: false,
shownEventID: 0,
searchQuery: ""
};
TypeError: onChange is not a function
onChange
src/components/SearchBox.jsx:12`enter code here`
9 | name="query"
10 | placeholder="search"
11 | value={value}
> 12 | onChange={e => onChange(e.currentTarget.value)}
| ^ 13 | />
14 | <a className="search-btn" href="">
15 | <i className="fa fa-search" />
You're setting the onChange
prop of the input element to a function called onChange
which might not be defined.
onChange={e => onChange(e.currentTarget.value)}
The second onChange
is not a function.
Render the SearchBox
component with the needed props, using the state value ( this.state.searchQuery
) that you are changing via onChange
instead of just this.searchQuery
(which you said you tried in your comment):
<SearchBox value={this.state.searchQuery} onChange={this.handleSearch}/>
This will update responsively as SearchBox
will now re-render every time searchQuery
changes in the parent state.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.