This is my first React app and I have read the official tutorial/doc and am following the guidelines there. I thought I had a decent understanding of the concepts but obviously I am missing something as I am unable to pass value and id back to parent component so I can do the grading in parent component.
Basically this is a simple quiz (or q & a) app where the array[0] is question and array[1] is answer: allProblems = [[q1,a1],[q2,a2], ...].
class ChildComponent extends React.Component {
inputAnswer(id, e) {
e.preventDefault();
this.props.onAnswer(e.target.value, id);
}
render() {
const { problem, id, answer } = this.props;
return (
<li>
{problem[0]} = <input value={answer} onChange={(e) => this.inputAnswer(id, e)} />
</li>
);
}
}
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
answer: null,
};
}
handleAnswer(answer, id) {
alert(id);
this.setState({
answer: answer,
})
}
render() {
const rows = [];
this.props.allProblems.forEach((problem, index) => {
rows.push(
<ChildComponent
key={index}
problem={problem}
id={index}
answer={this.state.answer}
correct={this.state.correct}
onAnswer={() => this.handleAnswer()}
/>
);
});
return (
<div>
<h1>Problems</h1>
<ul>{rows}</ul>
</div>
);
}
}
Thanks!