Answer the question
In order to leave comments, you need to log in
What is the best way to implement text animation in React?
It is necessary to make text animation, with automatic printing. The bottom line is that there is a static part of the text and the second part changes dynamically (several options are printed and deleted in turn). Implemented this using SetTimeout. During rendering, depending on the condition, the state changes with a delay.
The whole problem is that with certain actions on the site (scrolling to the mobile or opening the menu), the animation starts to wildly accelerate.
I don't understand what the problem is.
export default class AutoType extends React.Component {
constructor() {
super();
this.state = {
mainText: 'Учитесь онлайн',
supplText: [
'тому, что нужно',
'на индивидуальных занятиях',
'с классными преподавателями',
'на удобной платформе',
`через приложение в\u00A0смартфоне`
],
countMain: 0,
countSuppl: 0,
supplNum: 0,
isDeleting: false
};
this.writer = null;
}
componentWillUnmount() {
clearInterval(this.writer);
}
render() {
let timer = (Math.random() * 100).toFixed(0);
let nextString = false;
if (this.state.supplText[this.state.supplNum].length > 20) {
nextString = true;
} else if (this.state.supplText[this.state.supplNum].length < 20) {
nextString = false;
}
if (this.state.countSuppl === this.state.supplText[this.state.supplNum].length) {
timer = 2500;
}
if (this.state.isDeleting) {
timer = 20;
}
this.writer = setTimeout(() => {
if (this.state.isDeleting && this.state.countSuppl > 0) {
this.setState({
countSuppl: this.state.countSuppl - 1
});
} else if (
this.state.isDeleting &&
this.state.countSuppl === 0 &&
this.state.supplNum < this.state.supplText.length - 1
) {
this.setState({
supplNum: this.state.supplNum + 1,
isDeleting: false
});
} else if (this.state.countSuppl < this.state.supplText[this.state.supplNum].length && !this.state.isDeleting) {
this.setState({
countSuppl: this.state.countSuppl + 1
});
} else if (this.state.countSuppl >= this.state.supplText[this.state.supplNum].length) {
this.setState({
isDeleting: true
});
} else if (this.state.supplNum === this.state.supplText.length - 1 && this.state.countSuppl === 0) {
this.setState({
countMain: 0,
supplNum: 0,
isDeleting: false
});
}
}, timer);
return (
<ResultString
nextString={nextString}
mainText={this.state.mainText}
secondText={this.state.supplText[this.state.supplNum].substr(0, this.state.countSuppl)}
/>
);
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question