In reactjs, I am displaying a cursor before the current letter in a typing test app. I am using the current letter’s absolute positions to position the cursor. It is working, but when used in mobile phone there is slightly smaller value of top position of the letter
const rect = spanRef.current.getBoundingClientRect(); setCurrentCharacterPos({top: rect.top, left: rect.left});
Tried logging the value in both devices and got follwing result –
Mobile: 212.72727966308594
Desktop: 213.09091186523438
Code –
<div onClick={handleContainerClick} ref={containerRef} className={`border leading-[3em] max-h-[10rem] h-[10rem] overflow-hidden ${showTextTransition ? 'opacity-0' : 'opacity-1'} transition duration-100`}>
{!showTextTransition && (
<>
{sampleText.split('').map((char, index) => {
return <Letter key={index} windowWidth={windowWidth} scrollableDivScrollTop={scrollableDivScrollTop} char={char} index={index} setCurrentCharacterPos={setCurrentCharacterPos} currentIndex={inputText.length} isIncorrect={charactersStatus.length > 0 ? charactersStatus[index] !== null && !charactersStatus[index] : false} />
})}
{/* simulating an extra line */}
<span className="text-4xl whitespace-pre"> </span>
{
(inputText.length < sampleText.length && (currentCharacterPos.left >= 0 && currentCharacterPos.top+4 >= containerRef.current.getBoundingClientRect().top)) &&
<div className={`bg-light-active dark:bg-dark-active inline-block h-12 w-[2px] absolute transition-all duration-100 ${!startTime ? 'animate-fade' : ''}`} style={{ left: `${currentCharacterPos.left}px`, top: `${currentCharacterPos.top + 3}px` }}></div>
}
</>
)}
</div>
Letter Component –
import { useEffect, useRef, useState } from "react"
export default function Letter({ char, index, currentIndex, isIncorrect, setCurrentCharacterPos, scrollableDivScrollTop, windowWidth }) {
const spanRef = useRef(null);
useEffect(()=>{
if(index===currentIndex && spanRef.current){
const rect = spanRef.current.getBoundingClientRect();
setCurrentCharacterPos({top: rect.top, left: rect.left});
}
}, [currentIndex, index, spanRef, scrollableDivScrollTop, windowWidth]);
return (
<span className="text-4xl" ref={spanRef}>
<span className={`transition duration-100 ${isIncorrect ? 'text-light-danger dark:text-dark-danger' : (index < currentIndex ? 'text-light-hover dark:text-dark-hover' : 'text-light-icon dark:text-dark-icon')}`}>{char}</span>
</span>
)
}
Aman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.