Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick problem with typescript 3.33 and react

Tags:

typescript

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?

like image 648
Bussiere Avatar asked Dec 13 '22 12:12

Bussiere


1 Answers

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>
}
like image 117
Daniel Hilgarth Avatar answered Dec 28 '22 22:12

Daniel Hilgarth