I have a React Native component that needs to show an Animation with the letters of a string printing letter by letter. So, logically, I need to update a React state hook inside a loop appending each character of the string to it in a 1 second interval. What I have so far is:
let [placeholder, change_placeholder] = React.useState('');
const placeholder_print = () => {
let temp = "Search for anything"
console.log("Value of temp is now: " + temp)
console.log("Length of string: " + temp.length)
for (let i = 0; i < temp.length; i++) {
console.log("Selected character is: " + temp.charAt(i))
change_placeholder(placeholder.concat(temp.charAt(i)))
console.log("Placeholder is now: " + placeholder)
}
}
and the React component with the state hook in it:
<View>
<Text>{placeholder}</Text>
</View>
Yes, I know that this won't animate. But in the end of the for
, the value of placeholder
should logically be the string itself, right? If so, I might be able to get around the animation part with setTimeout()
inside the for loop to run this every second. But, this is the output when placeholder_print()
is run:
[Fri Jan 15 2021 16:29:30.166] LOG Value of temp is now: Search
[Fri Jan 15 2021 16:29:30.168] LOG Length of string: 6
[Fri Jan 15 2021 16:29:30.169] LOG Selected character is: S
[Fri Jan 15 2021 16:29:30.170] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.170] LOG Selected character is: e
[Fri Jan 15 2021 16:29:30.170] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.171] LOG Selected character is: a
[Fri Jan 15 2021 16:29:30.171] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.171] LOG Selected character is: r
[Fri Jan 15 2021 16:29:30.172] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.172] LOG Selected character is: c
[Fri Jan 15 2021 16:29:30.172] LOG Placeholder is now:
[Fri Jan 15 2021 16:29:30.173] LOG Selected character is: h
[Fri Jan 15 2021 16:29:30.173] LOG Placeholder is now:
When running a similar logic in Python or even vanilla JavaScript with no state hooks, this works fine. I don't know if this needs to be implemented with the <Animated>
component in React Native, or if it's some fundamental difference in the way React state hooks work. I'm stuck here and helping hands will be upvoted.