Do I need to bind event handlers to `this` with TypeScript + React?

Viewed 2922

I have a component with a simple button handler method. If I don't bind the onClick handler to this in the constructor (or inline on the onClick itself), then I get an error because the context of the handleAdd method is not the instance where my component's state is...

I understand how the bind works, but is there a workaround to avoid having to use bind all over the place with TypeScript + React?

export class TodoList extends React.Component<ITodoListProps, Partial<ITodoListState>> {
    constructor(props: ITodoListProps) {
        super(props);
        this.state = { items: props.items };

        this.handleAdd.bind(this);
    }

    public render() {
        return (
            <div>
                <button onClick={this.handleAdd}>Add</button>
                <ul>
                    {this.state.items.map((todo, i) => {
                        return <TodoItem key={i} name={todo.name} />
                    })}
                </ul>
            </div>
        );
    }

    handleAdd(e: any) {
        this.setState({
            items: [...this.state.items, { name: "foo" }]
        });
    }
}
2 Answers
Related