I've made this in straight JS and I'm trying to implement the same sort of thing on a Gatsby site by translating it into React. Basically, the point is to have the letters appear in a random order but in their proper places.
The point at which I'm stuck (I'm pretty new to React) is how to create and access the set of elements (spans) in the randomized order to be able to get them to show in that order.
class about extends Component {
constructor(props) {
super(props);
this.state = {
aboutText: "This is a test of the emergency broadcast system",
aboutElements: []
}
}
shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
render() {
const arrLetters = this.state.aboutText.split("");
let arrNumbers = Array.from(Array(arrLetters.length).keys());
arrNumbers = this.shuffleArray(arrNumbers);
const arrSpans = arrLetters.map((letter, index) => <span key={index} id={"letter" + index}>{letter}</span>);
console.log(arrSpans)
this.setState({ aboutElements: arrSpans })
arrNumbers.forEach(function(item, index) {
let targetSpan = arrSpans.filter( el => el.key == item);
// NEED TO MAKE THE LETTER VISIBLE HERE
});
return (
<section id="about" className={styles.about}>
<div className="container">
<p>{ this.state.aboutElements }</p>
</div>
</section>
)
}
}
export default about
So what I'm creating the array of letters, turn it into an array of elements, but the moment I try to put it into a state I get this error:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside
componentWillUpdateorcomponentDidUpdate. React limits the number of nested updates to prevent infinite loops.
What am I doing wrong?