Home > Software design >  TypeScript / React - Trying to Create My Own Button Issue - Function Signature Problem
TypeScript / React - Trying to Create My Own Button Issue - Function Signature Problem

Time:10-08

I'm trying to create a simple button in React / TypeScript.

I'm not sure where I am getting the syntax for this incorrect.

Editors don't seem to like the ' => void ' part of my signature.

My goal is to be able to pass down a "clear state" type handler from any parent component.

import React from 'react';
import ClearIcon from '@material-ui/icons/Clear';

// problem is on this line
export function ClearButton(props: {onClick: (React.MouseEvent<HTMLElement>) => void}) {
  return (<span
            onClick={(e) => { props.onClick(e) }}>
    <ClearIcon /></span>);
}

CodePudding user response:

I believe you forgot the name of the function's parameter.
Example:

onClick: (e: React.MouseEvent<HTMLElement>) => void

Also, the actual onClick on the span should probably be assigned like so:

onClick={(e) => props.onClick(e)}>

Alternatively, you could use a shorter syntax in this case, if you prefer.

onClick={props.onClick}>

So your code becomes:

export function ClearButton(props: {onClick: (e: React.MouseEvent<HTMLElement>) => void}) {
  return (
     <span onClick={(e) => props.onClick(e)}>
        <ClearIcon />
     </span>
  )
}
  • Related