I have the following class component
...
constructor(props) {
super(props);
...
this.currentlyEditedInput = React.createRef()
}
...
onClick(id, column) {
return (event) => {
...
let { clientX, clientY } = event;
let repeatClick = ( true /*repeat needed*/) ? function() {
let click = new MouseEvent("click", {
clientX,
clientY
});
console.log(this.currentlyEditedInput.current.firstChild.tagName) // INPUT
console.log(this.currentlyEditedInput.current.firstChild.dispatchEvent) // function dispatchEvent()
this.currentlyEditedInput.current.firstChild.dispatchEvent(click) // nothing happens
} : undefined;
...
this.setState(/*new state*/, repeatClick); // when state is updated new input is rendered
...
}
}
...
render() {
...
return (
...
<TableCell
className={classes.cell}
key={column.name}
onClick={ this.onClick(row.id, column) }
>
...
<Input
ref={this.currentlyEditedInput}
autoFocus
...
/>
...
</TableCell>
...
)
}
When a table cell is clicked a new input with some value appears inside it, but the cursor is in the end of the input so the user has to click one more time. I want to make the cursor appear where the user clicks. So I dispatch the same click event in the callback (second argument of setState
), but calling dispatchEvent
does not seem to change anything.
May be this task should be solved in a completely different way. What is the correct way to do it in React?