reactjsreduxrte

Rich Text Editor Cursor doesn't move making the text be typed backwards


I have a RTE inside a react functional component and for some reason the cursor has stopped moving ahead as the text is typed causing the text to be typed backwards. Now, I have figured where the issue is but I don't have a solution. I did find this issue that has the same problem which they fixed with adding setContentFromString(nextProps.value) when updating the state but I get the following error

TypeError: react_rte__WEBPACK_IMPORTED_MODULE_5___default.a.setContentFromString is not a function

Here is my component.

   export default props => {
        const { value, onChange, error, row, readOnly, className, ...rest } = props;
        const [internalValue, setInternalValue] = React.useState(
            value ? RichTextEditor.createValueFromString(unescape(value), 'html') : RichTextEditor.createEmptyValue()
        );
    
        React.useEffect(() => {
            setInternalValue(
                value ? RichTextEditor.createValueFromString(unescape(value), 'html') : RichTextEditor.createEmptyValue()
            );
        }, [value]);
    
        const classes = useStyles({ row });

// the problem area
        function change(value) {
            setInternalValue(value);
            if (onChange) {
                const trimmed = value.toString('markdown').trim();
                if (trimmed.length === 0 || (trimmed.length === 1 && trimmed.charCodeAt(0) === 8203)) {
                    onChange(null);
                } else onChange(escape(value.toString('html')));
            }
        }
    
        return (
            <RichTextEditor
                customStyleMap={customStyles}
                toolbarConfig={toolbarConfig}
                value={internalValue}
                onChange={change}
                readOnly={readOnly}
                toolbarClassName={classes.toolbar}
                editorClassName={clsx(readOnly ? null : classes.editor, error ? classes.error : null)}
                className={clsx(classes.root, className)}
                {...rest}
            />
        );
    };

Solution

  • The internalValue was accidentally set to a value that was changing with every keystroke hence triggering the useEffect and eventually setting the cursor to position 1. By using React.useRef I was able to compare the changes and get this working.