I'd like to focus on the input field as soon as it's rendered. The pitfall is that I can't focus on it in the startEdit method because there is no reference to the element at the moment I want to focus, so this.editField is undefined. I could probably create <Input />
component and implement focusing in it's componentDidMount method but I wonder if there is a more concise way to do that?
class TodoItem extends React.Component<IProps, IState> {
editField ?: HTMLInputElement;
constructor() {
super();
this.state = {
isEditActive: false
};
}
private startEdit(): void {
this.setState({isEditActive: true});
this.editField.focus();
}
private finishEdit(): void {
this.setState({isEditActive: false});
}
public render(): JSX.Element {
const {text, deleteTodo} = this.props;
const {isEditActive} = this.state;
return(
<li className='todo-item'>
{isEditActive ?
<input ref={(input) => { this.editField = input; }} onBlur={this.finishEdit} type='text'/>
: text
}
<span onClick={deleteTodo} className='delete'>X</span>
<span onClick={this.startEdit} className='edit'>Edit</span>
</li>
);
}
}