I am experimenting with React: I have 2 arrays (array1 and array2) containing some words. I would like to initialize my React state array called "sentences" by looping the 2 arrays (array1 and array2) and pushing a component "Sentence" into the state array at each iteration. This is my code:
import React, { Component } from "react";
import "./App.css";
import Sentence from "./Sentence.js";
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() {
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
let newArray = this.state.sentences.slice();
newArray.push( <Sentence word1={array1[i]} word2={array2[j]} /> );
this.setState({ sentences: newArray });
}
}
}
render() {
return (
<div>
{this.state.sentences[0]}
{this.state.sentences[1]}
{this.state.sentences[2]}
</div>
);
}
}
export default App;
And this is Sentence.js:
import React, { Component } from "react";
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}
</div>
);
}
}
export default Sentence;
However, in browser, I only see:
First word: car
Second word: yeah
My desired result would be to see the first and second word for the first 3 components of the state array (sentences).
setStateis async.this.state.sentenceswon't be updated inside the loop. Build the Array first and then push it all at once.