I have 2 arrays (array1 and array2) containing some words. The 2 arrays are looped and, at each iteration, a React component "Sentence" (with the props being a word from each array) is pushed to the state array "sentences". The first 5 elements of the array are displayed on browser.
var array1 = ["hello", "some", "words", "house", "garden", "car"];
var array2 = ["other", "bag", "of", "words", "oh", "yeah"];
class App extends Component {
constructor(props) {
super(props);
this.state = {
sentences: []
};
}
componentDidMount() {
let sentences = this.state.sentences.slice();
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
sentences.push(<Sentence word1={array1[i]} word2={array2[j]} />);
}
}
this.setState({ sentences: sentences });
}
shuffle = () => {
let temp = this.state.sentences.slice();
for (let i = temp.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * (i + 1));
[temp[i], temp[j]] = [temp[j], temp[i]];
}
this.setState({ sentences: temp });
};
render() {
return (
<div>
{this.state.sentences[0]}
{this.state.sentences[1]}
{this.state.sentences[2]}
{this.state.sentences[3]}
{this.state.sentences[4]}
<Button variant="primary" onClick={this.shuffle}>
Shuffle
</Button>
</div>
);
}
}
And Sentence.js
class Sentence extends React.Component {
constructor(props) {
super(props);
this.state = {
word1: this.props.word1,
word2: this.props.word2
};
}
render() {
return (
<div>
First word: {this.state.word1}
<br />
Second word: {this.state.word2}
<br />
<br />
</div>
);
}
}
The issue: when shuffling the array, the order of "sentences" shown in browser doesn't change.
(The shuffling algorithm is from this stackoverflow post)