-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix issue where cursor position is lost when shortcuts are used #3
Comments
In this given code, it looks like you're using the However, you're trying to update the cursor's position manually using direct DOM manipulation, which is not recommended in React. Instead, we should use React's mechanisms to control the state of the component. For the Here is your updated import './Code.css'
import React, { useState, useEffect } from 'react';
import Editor from 'react-simple-code-editor';
import { highlight, languages } from 'prismjs/components/prism-core';
import 'prismjs/components/prism-clike';
import 'prismjs/components/prism-javascript';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-markup';
import Symbols from './Symbols'
const Code = ({type, tab, callback}) => {
const [currentCode, setCurrentCode] = useState(
JSON.parse(localStorage.getItem(type)) || ''
)
const [cursorPosition, setCursorPosition] = useState(null);
const visible = tab === type
useEffect(() => {
localStorage.setItem(type, JSON.stringify(currentCode))
callback(currentCode)
}, [currentCode])
useEffect(() => {
if(cursorPosition !== null){
const el = document.querySelector(`#${tab} textarea`)
el.selectionStart = el.selectionEnd = cursorPosition;
el.focus();
}
}, [cursorPosition])
const insertSymbol = (symbol) => {
const el = document.querySelector(`#${tab} textarea`)
const start = el.selectionStart
const end = el.selectionEnd
const text = el.value
const before = text.substring(0, start)
const after = text.substring(end, text.length)
setCurrentCode(before + symbol + after)
setCursorPosition(start + symbol.length)
}
const renderEditor = () => {
// Editor rendering code...
}
return (
<div className={visible ? 'visible' : 'hidden'}>
<Symbols className='symbols' insertSymbol={insertSymbol} />
{ renderEditor() }
</div>
)
}
export default Code; In this code:
Remember that direct DOM manipulation in React should be the last resort as it breaks the normal flow of React's virtual DOM diffing and re-rendering process. It's better to use the React's lifecycle methods (like |
No description provided.
The text was updated successfully, but these errors were encountered: