I'm new to using typescript with react. I'm trying to handle the onClick event of a list item and I get the error "Argument of type 'number' is not assignable to parameter of type 'ChangeEvent'." I'm calling a function to handle click event but it doesn't work. I'm not sure how to properly do it. Below is the code I'm using to try to accomplish this.
function onClick(e: React.ChangeEvent<HTMLInputElement>) {
setActiveSuggestion(0);
setFilteredSuggestions([]);
setShowSuggestions(false);
setUserInput(e.currentTarget.value);
};
let suggestionsListComponent;
if (showSuggestions && userInput) {
if (filteredSuggestions.length) {
suggestionsListComponent = (
<ul className="suggestions">
{filteredSuggestions.map((suggestion, index) => {
let className;
// Flag the active suggestion with a class
if (index === activeSuggestion) {
className = "suggestion-active";
}
return (
<li className={className} key={suggestion} onClick={() => onClick(activeSuggestion)}>
{suggestion}
</li>
);
})}
</ul>
);
} else {
suggestionsListComponent = (
<div className="no-suggestions">
<em>No suggestions, you're on your own!</em>
</div>
);
}
}
CodePudding user response:
The function is expecting an event object:
function onClick(e: React.ChangeEvent<HTMLInputElement>) {
You're passing it a number:
onClick={() => onClick(activeSuggestion)}
The event type doesn't make sense for an <li>
element, which is neither an input nor has a change event. It looks like you just want to expect a number:
function onClick(value: Number) {
And that, within the function, your intent is to set a state value to that number:
setUserInput(value);
CodePudding user response:
pass this way on element itself onClick={(e) => onClick(e,activeSuggestion)}
and on onClick method definition receive (e,param) two parameters;
CodePudding user response:
I found the solution after @David post. I changed the following function parameter to a string and then passed the suggestion string to it and it worked.
function onClick(suggestion: string)
<li className={className} key={suggestion} onClick={() => onClick(suggestion)}>
{suggestion}
</li>