I am trying to print out a raising text segment in React, but every char gets printed twice.
So hopefully someone has an idea.
index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import Test from './test.js';
function Root(){
return(
<React.StrictMode>
<Test/>
</React.StrictMode>
)
}
ReactDOM.createRoot(document.getElementById('root')).render(<Root/>);
test.js
import {useCallback,useEffect,useState} from 'react';
export default function Test(){
const [outText,setOutText] = useState('');
const drawText = useCallback(text=>{
let index=0;
let textInterval;
const callback = ()=>{
if (index>=text.length-1){
clearInterval(textInterval);
return;
}
setOutText(t=>{
if (text[index]==='n'){
return t+'<br>';
} else {
return t+text[index];
}
});
index++;
};
textInterval=setInterval(callback,20);
});
useEffect(()=>{
const text = `
a text is written here
and should be printed step by step
`.split('');
drawText(text);
},[])
return (
<div id="test">
<div className="out-text" dangerouslySetInnerHTML={{__html:outText}} />
</div>
);
}
Every character should be appended to outText
only once and not twice. Please avoid solutions that rely on index % 2
as they will not resolve my issue.
2
Answers
I haven’t been able to debug your code and find the problem, but I’d like to offer an alternative solution. The following uses a hook to manage the value of the string.
Example usage would be:
A more React idiomatic solution: