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" }]
});
}
}
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" }]
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With