To address this issue, I introduced a new function that directs the cursor's focus towards the user by utilizing the useEffect hook with a listener attached to the content hook. Here is how the function works:
function focus() {
const contentEle = document.getElementById('content');
const range = document.createRange();
const selection = window.getSelection();
range.setStart(contentEle, contentEle.childNodes.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
useEffect(() => {
focus();
}, [content]);
This code now includes the newly created function.
// Importing necessary dependencies
import React from "react";
import { useState, useEffect } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
faBold,
faCode,
faFileCode,
faFilm,
faImage,
faItalic,
faLink,
faList,
faListOl,
faQuoteRight,
faStrikethrough,
faUnderline,
} from "@fortawesome/free-solid-svg-icons";
import "./textEditor.css";
const TextEditor = () => {
// State hooks declaration
const [content, setContent] = useState("");
const [isBold, setIsBold] = useState(false);
const [isItalic, setIsItalic] = useState(false);
const [isUnderline, setIsUnderline] = useState(false);
const [isStrikeThrough, setStrikeThrough] = useState(false);
const [isBlockquote, setIsBlockquote] = useState(false);
const [isHeading1, setIsHeading1] = useState(false);
const [isHeading2, setIsHeading2] = useState(false);
const [isOrderedList, setIsOrderedList] = useState(false);
const [isUnorderedList, setIsUnorderedList] = useState(false);
const [isInlineCode, setIsInlineCode] = useState(false);
const [isCodeBlock, setIsCodeBlock] = useState(false);
// Function to handle text formatting
const handleFormat = (style, value = null) => {
// Toggling state for corresponding style
switch (style) {
case "bold":
setIsBold(!isBold);
break;
case "italic":
setIsItalic(!isItalic);
break;
case "underline":
setIsUnderline(!isUnderline);
break;
// Other cases omitted for brevity
}
// Applying the selected style
document.execCommand(style, false, value);
};
// Defining the focus function
function focus() {
const contentEle = document.getElementById('content');
const range = document.createRange();
const selection = window.getSelection();
range.setStart(contentEle, contentEle.childNodes.length);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
// Triggering focus on content change
useEffect(() => {
focus();
}, [content]);
return (
<!-- Component structure and button implementations here -->
);
};
export default TextEditor;
For more details and to access the updated project with this solution, you can visit the following link: https://github.com/pablosalazzar/stackoverflow-answer-2