I'm trying to create an animated text char by char to bounce from right to left, but I need to add a different delay to each char. So far the animation looks nice the problem is that the delay is not updating for each char.
This is my code:
import React from "react";
import { useSprings, animated } from "react-spring"
import s from '../../styles/pages/home.module.scss'
// HERE CREATE AN ARRAY CHAR BY CHAR INCLUDING " ", FROM A STRING
let textString = "Random text for this example."
let textArray = Array.from(textString)
const HeroText = () => {
const springs = useSprings(
textArray.length,
textArray.map((item, i)=> ({
id : i,
from : {opacity: 0, translateX : '1000px'},
to: {opacity: 1, translateX : '0px'},
delay: (0.5 + i / 10),
config: { mass: 4, tension: 200, friction: 30}
}))
)
let elements = springs.map((spring, i) => {
console.log(spring)
return(
<animated.span key={i} style={{...spring}}>
{textArray[i] === ' ' ? <span> </span> : textArray[i]}
</animated.span>
)
})
return(
<div className={s.heroText}>
<h1 className={"my-heading divided-heading"}>
{elements}
</h1>
</div>
)
}
export default HeroText
On the console.log(spring), I can actually see that all the objects have different "delay" values, but on render they all animate at the same time, so it does not look like the text is animated char by char.
I have read the react-spring documentation but I did not find it to be very helpful, so if someone can help me understand what I'm missing I would be glad. Thanks!
so after allot of research I found out that the best way to do what I was trying to do was to use "useTransition".
This was the final code, working properly.
import React from "react";
import { animated, useTransition } from "react-spring"
import s from '../../styles/pages/home.module.scss'
// HERE CREATE AN ARRAY CHAR BY CHAR INCLUDING " ", FROM A STRING
let textString = "Hi, I'm Stephane Ribeiro. Want to como on a full stack journey trough my mind?!"
let textArray = Array.from(textString)
let objArray = textArray.map((item, i) => {
return ({
char : item,
key: i
})
})
const HeroText = () => {
const tranConfig = {
from : {opacity: 0, translateX : '1000px'},
enter: {opacity: 1, translateX : '0px'},
config: { mass: 4, tension: 200, friction: 30},
trail: 50
}
const transition = useTransition(objArray, tranConfig)
let elements = transition((values, item) => {
return(
<animated.span key={item.key} style={values}>
{item.char === ' ' ? <span> </span> : item.char}
</animated.span>
)
})
return(
<div className={s.heroText}>
<h1 className={"my-heading divided-heading"}>
{firstElements}
</h1>
</div>
)
}
export default HeroText