Naresh
Naresh

Reputation: 25743

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>
    }
}

Upvotes: 10

Views: 10160

Answers (1)

Cristi Mihai
Cristi Mihai

Reputation: 2565

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;
    //
}

Upvotes: 21

Related Questions