I'm trying to create something like a text editor online, based in React. I would like to add near the textarea a div that counts the line that I am currently using. So, I created a funciotn that counts the lines in the textarea, then added an element that gets that number and create that list. The problem is that when I render, it creates the list corectly, but when I write something, it doesn't rerender. The problem it that when I write something, it doesn't rerender. Here is my code:
const Editor = () => {
const [text, setText] = useState('//');
const handleChanges = (e) => {
setText(e.target.value);
}
const countLine = () => {
let lines = text.split(/\r|\r\n|\n/);
let count = lines.length;
return count;
}
return <>
<form className="editor">
<div>
<li>{/*this is where i create the numbers*/}
{<ul>{Array.from(Array(countLine), (e, i) => {
return <li key={i}>{i}</li>
})}</ul>}
</li>
</div>
<textarea name="text" value={text} className="editorText" onChange={handleChanges} spellCheck="false"
id = {bg}></textarea>
</form>
</>
}
I would like that when I make the change, the code makes automatically the update to the number of line, but I can't work with the handleChanges funtion, or at least, I didn't find how. Can someone help me? Thanks
Resolved adding a new state value, that every times that there is a change, is recalculated. Then , the numbers are recreated. Here is the code:
import { useState } from "react";
const Editor = () => {
const [text, setText] = useState('//Your code');
const [line, setLine] = useState(1);
const handleChanges = (e) => {
setText(e.target.value);
setLine(countLine);
}
const countLine = () => {
let lines = text.split(/\r|\r\n|\n/);
let count = lines.length;
console.log(count);
return count;
}
return <>
<form className="editor">
<div>
<div class="number">
<ul>
{Array.from(Array(line), (e, i) => {
return <li key={i}>{i + 1}</li>
})}
</ul>
</div>
</div>
<textarea name="code" value={text} className="editorText" onChange={handleChanges} spellCheck="false"
id = {bg}></textarea>
</form>
</>
}
export default Editor;