I’m having trouble changing the characters in the Monaco Editor that don’t match a specific variable (text1). My goal is to apply a bg-red-600 style only to the incorrect characters, but if there’s an error, all subsequent characters are highlighted with bg-red-600, even if they are correct.
I asked ChatGPT for help, but the solution it provided overwrote all the text in the editor and caused performance issues. Any advice on how to fix this efficiently?
This is my code:
import Editor from '@monaco-editor/react';
import { getTheme } from '../models/StylesEditor';
import { useEditorContext } from '../context/EditorContext';
export const CodeEditor = () => {
const text1 = `const num1 = 25;
const num2 = 5;
const result = num1 / num2;
console.log(result)`;
const textLines = text1.split('n')
const { config, themeEditor } = useEditorContext();
const eventKey = useRef(null);
const monacoObj = useRef(null);
const [value, setValue] = useState('');
const onValueChange = (newValue, event) => {
eventKey.current = event;
setValue(newValue);
};
const handleEditorDidMount = (editor, monaco) => {
monaco.editor.defineTheme('my-theme', getTheme(themeEditor));
monaco.editor.setTheme('my-theme');
monacoObj.current = { editor, monaco };
};
useEffect(() => {
if (!monacoObj.current) return;
const { editor, monaco } = monacoObj.current;
const e = eventKey.current?.changes[0]
const eR = e.range;
const verification = textLines[eR.startLineNumber - 1][eR.startColumn - 1] !== e.text && e.text !== ""
const classDeco = verification ? 'bg-red-600' : 'bg-transparent'
const newDecoration = {
range: new monaco.Range(eR.startLineNumber, eR.startColumn, eR.startLineNumber, eR.startColumn + 1),
options: { inlineClassName: `${classDeco}` }
}
editor.deltaDecorations([], [newDecoration])
}, [value]);
return (
<div className="h-full w-full flex items-center justify-center">
<Editor
{...config}
onMount={handleEditorDidMount}
value={value}
onChange={onValueChange}
/>
</div>
);
};