1

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?

havon
  • 21
  • 3
  • Does this answer your question? [React JS onClick event handler](https://stackoverflow.com/questions/28511207/react-js-onclick-event-handler) – Viswanath Lekshmanan May 21 '20 at 11:52
  • @ViswanathLekshmanan, no it doesn't. My question is about dispatching events, not handling them. – havon May 21 '20 at 12:14
  • You can focus the input using https://stackoverflow.com/questions/28889826/how-to-set-focus-on-an-input-field-after-rendering . B/W how do you track on which position the user was keeping the cursor ? – Viswanath Lekshmanan May 21 '20 at 12:21
  • @ViswanathLekshmanan, "how do you track on which position the user was keeping the cursor ?" - `let { clientX, clientY } = event;` – havon May 21 '20 at 13:43
  • Doesn't the value change after the UI alteration (Addition if new component) ? – Viswanath Lekshmanan May 22 '20 at 07:03

0 Answers0