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?

5
  • Does this answer your question? React JS onClick event handler Commented May 21, 2020 at 11:52
  • @ViswanathLekshmanan, no it doesn't. My question is about dispatching events, not handling them. Commented May 21, 2020 at 12:14
  • You can focus the input using stackoverflow.com/questions/28889826/… . B/W how do you track on which position the user was keeping the cursor ? Commented May 21, 2020 at 12:21
  • @ViswanathLekshmanan, "how do you track on which position the user was keeping the cursor ?" - let { clientX, clientY } = event; Commented May 21, 2020 at 13:43
  • Doesn't the value change after the UI alteration (Addition if new component) ? Commented May 22, 2020 at 7:03

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.