I am trying to animate text with React. Like a typewriter. I am using setTimeout and setState. Here is my code. Is there a way to make it faster and with smoother animation? Thanks
const [text, setText] = useState<string>(' ')
const animateText = (direction: boolean) => {
description.substring(120, description.length)
const tick = description.length - 120
console.log('direction', direction)
if (direction) {
for (let index = 0; index < tick; index++) {
setTimeout(() => {
setText(description.substring(120, index))
}, index * 0.01)
}
} else {
for (let index = 0; index < tick; index++) {
setTimeout(() => {
setText(description.substring(120, description.length - index))
}, index * 0.01)
}
}
}
Your code is missing some attributes like the event that triggers the animatedText. But triggering it on first component load (see the useEffect) and adding a time rate (index * 50) based on the previous timeout, you can do this:
const {
useState,
useCallback,
useEffect
} = React;
const description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
const Component = () => {
const [text, setText] = useState(' ')
const animateText = useCallback((direction) => {
const max = description.length;
for (let index = 0; index < max; index++) {
const startIndex = direction ? 0 : max
const endIndex = direction ? index : max - index
setTimeout(() => {
setText(description.substring(startIndex, endIndex))
}, index * 50)
}
}, [])
useEffect(() => {
animateText(true)
}, [animateText])
return text
}
// Render it
ReactDOM.render( < Component / > ,
document.getElementById("react")
);
#react {
width: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react"></div>