Rendering a component multiple times with different props in React
Here is the correct syntax:
import React, { Component } from 'react';
import Panel from './components/Panel';
import Results from './components/Results';
import Intro from './components/Intro';
const questionsMap = [0, 1, 2, 3];
class React extends Component {
constructor (props) {
super (props);
this.state = {
questions: ['question1', 'question2', 'question3', 'question4'],
answers: ['answers1', 'answers2', 'answers3', 'answers4']
}
this.onSelect = this.onSelect.bind(this);
}
onSelect(value) {
/* Some code for when buttons are clicked */
}
render () {
return (
<div>
<Intro />
{questionsMap.map(i => {
return <Panel question={this.state.questions[i]} answers={this.state.answers[i]} onSelect={this.onSelect} />
})}
<Results />
</div>
);
}
}
export default App;
But there are a few things that are not exactly a good practice, I assume this is some sort of test so I don't expect that you will name one of your components React
.
On top of that you could simply map through the state, I would change the code a bit like this:
import React, { Component } from 'react'; import Panel from './components/Panel'; import Results from './components/Results'; import Intro from './components/Intro';
class React extends Component {
constructor (props) {
super (props);
this.state = {
questions: ['question1', 'question2', 'question3', 'question4'],
answers: ['answers1', 'answers2', 'answers3', 'answers4']
}
this.onSelect = this.onSelect.bind(this);
}
onSelect(value) {
/* Some code for when buttons are clicked */
}
render () {
return (
<div>
<Intro />
{this.state.questions.map((question, questionIndex) => {
return (<Panel
question={question}
answers={this.state.answers[questionIndex]}
onSelect={this.onSelect} />
)
})}
<Results />
</div>
);
} }
export default App;
Alternatively you could have an array of objects with a field named question and another named answer, just to give you another idea.