Naresh Naresh - 2 months ago 17
React JSX Question

Sending event handlers as props into a React component using TypeScript

I have the following code for a React component. What's the right way to declare the two

onClick
handlers passed into the component?

interface LoginFormProps {
loginClicked: ???? <--- onClick handler signature
cancelClicked: ???? <--- onClick handler signature
}

class LoginForm extends React.Component<LoginFormProps, {}> {
render() {
<form>
<button onClick={loginClicked}>
Login
</button>
<button onClick={cancelClicked}>
Cancel
</button>
</form>
}
}

Answer Source

I typically use:

interface ILoginFormProps {
    loginClicked: (ev) => void;
    //
}

But if you want to be really strict about your typing:

interface ILoginFormProps {
    loginClicked: (ev: React.MouseEvent<HTMLButtonElement>) => void;
    //
}