Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
    }
}
like image 431
Naresh Avatar asked Aug 18 '17 00:08

Naresh


1 Answers

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;
    //
}
like image 159
Cristi Mihai Avatar answered Oct 14 '22 23:10

Cristi Mihai