I'm trying to insert the following block on the cursor position:
Inserted Text
I've used following methods to get the exact cursor position:
my function buttonClick inserts it inside the line but is unable to recapture the changed cursor position when I try inserting it.
import React from "react";
import ReactDOM from "react-dom";
import jodit from "jodit";
import "./App.css";
import JoditEditor from "jodit-react";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
content: "",
pos: 0,
};
}
updateContent = (value) => {
this.setState({
content: value,
pos: window.getSelection().getRangeAt(0).startOffset,
});
};
buttonClick = (event) => {
var abc = this.state.content.slice(
this.jodit.selectionStart,
this.jodit.selectionEnd + 1
);
var startString = this.state.content.substring(0, this.state.pos + 3);
var endString = this.state.content.substring(this.jodit.selectionEnd);
console.log("abc" + startString + "::::::" + endString);
this.setState({
content: startString + '<a href="#">Inserted Text</a>' + endString,
});
};
config = {
readonly: false,
};
/**
* @property Jodit jodit instance of native Jodit
*/
jodit;
setRef = (jodit) => (this.jodit = jodit);
render() {
return (
<>
<JoditEditor
ref={this.setRef}
value={this.state.content}
config={this.config}
tabIndex={1} // tabIndex of textarea
onBlur={this.onFocusRemove}
onChange={this.updateContent}
/>
<button onClick={this.buttonClick}>insert</button>
</>
);
}
}
export default App;
I also tried the above code with this.jodit.selectionstart instead ofwindow.getSelection().getRangeAt(0).startOffset but issue remained.
According to what I analysed, onChange handler updates the cursor position whenever we input something, but when we change the cursor position it do not update it again.
Add below in the config object
config = {
readonly: false, // all options from https://xdsoft.net/jodit/doc/
events:
{
afterInit: (instance) => { this.jodit = instance; }
}
buttonClick = (event) => {
this.jodit.selection.insertHTML('<a href="">Anchor Tag</a>');
};
This way you will get instance of editor after afterInit. This should solve your problem.