Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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" }]
        });
    }
}
like image 400
mariocatch Avatar asked May 16 '17 00:05

mariocatch


1 Answers

but is there a workaround to avoid having to use bind all over the place with TypeScript + React?

Yes. Use an arrow function:

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

More

  • A quick video
  • More docs on arrow
like image 193
basarat Avatar answered Oct 05 '22 07:10

basarat