I am trying to use an onClick property on a link with TypeScript and React:
import * as React from 'react';
import { any } from 'prop-types';
function handleClick(this:any,name:React.ReactNode) {
console.log('The link was clicked.');
this.props.callbackFromParentSearch(name);
}
export const Suggestions = (props:any) => {
const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
<a href="#" onClick={handleClick(r.name)}>
<li key={r.id}>
{r.name}
</li>
</a>
))
return <ul>{options}</ul>
}
export default Suggestions
But this gives an error:
Type 'void' is not assignable to type '(event: MouseEvent) => void'.ts(2322) index.d.ts(1315, 9): The expected type comes from property 'onClick' which is declared here on type 'DetailedHTMLProps, HTMLAnchorElement>'
So how to use the onClick event properly in TypeScript & React?
You need to pass a function:
onClick={() => handleClick(r.name)}
However, even with that your code won't work, because your handleClick
function requires to be bound in a way that this
is an object that contains your props. That's not the case in your code.
Your component should work like that:
export const Suggestions = (props:any) => {
const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
<a href="#" onClick={() => props.callbackFromParentSearch(r.name)}>
<li key={r.id}>
{r.name}
</li>
</a>
))
return <ul>{options}</ul>
}
or like this:
function handleClick(props: any, name: React.ReactNode) {
console.log('The link was clicked.');
props.callbackFromParentSearch(name);
}
export const Suggestions = (props:any) => {
const options = props.results.map((r: { id: React.Key; name: React.ReactNode; }) => (
<a href="#" onClick={() => handleClick(props, r.name)}>
<li key={r.id}>
{r.name}
</li>
</a>
))
return <ul>{options}</ul>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With