<div id="app"></app>
class Survey extends React.Component {
constructor(props) {
super(props);
this.state = {
questions: [ 'Are you a developer ?', 'Do you like bananas ?' ],
answers: []
};
}
render() {
return (
<React.Fragment>
{ this.state.questions.map((question, index) => <QuestionContainer key={index} label={question}/>) }
</React.Fragment>
);
}
}
const Question = props =>
<p>
<span>{props.label}</span>
<label><input type="radio" name="answer" value="true" onChange={props.answerQuestion}/>Yes</label>
<label><input type="radio" name="answer" value="false" onChange={props.answerQuestion}/>No</label>
</p>
class QuestionContainer extends React.Component {
constructor(props) {
super(props);
this.state = { answered: false };
this.answerQuestion = this.answerQuestion.bind(this);
}
answerQuestion({target}){
let answer = target.value === 'true' ? true : false;
this.setState({ answered: true, answer });
}
render() {
if(this.state.answered) {
return <p>You already answered this question ({this.state.answer ? 'yes' : 'no'})</p>
}
return <Question label={this.props.label} answerQuestion={this.answerQuestion}/>
}
}
ReactDOM.render(
<Survey/>,
document.getElementById('app')
);
View Compiled
This Pen doesn't use any external CSS resources.