I'm making a primitive quiz app with 3 questions so far, all true or false. In my handleContinue
method there is a call to push the users input from a radio form into the userAnswers
array. It works fine for the first run of handleContinue
, after that it throws an error: Uncaught TypeError: this.state.userAnswers.push is not a function(…)
import React from react
export default class Questions extends React.Component {
constructor(props) {
super(props)
this.state = {
questionNumber: 1,
userAnswers: [],
value: ''
}
this.handleContinue = this.handleContinue.bind(this)
this.handleChange = this.handleChange.bind(this)
}
//when Continue button is clicked
handleContinue() {
this.setState({
//this push function throws error on 2nd go round
userAnswers: this.state.userAnswers.push(this.state.value),
questionNumber: this.state.questionNumber + 1
//callback function for synchronicity
}, () => {
if (this.state.questionNumber > 3) {
this.props.changeHeader(this.state.userAnswers.toString())
this.props.unMount()
} else {
this.props.changeHeader(Question + this.state.questionNumber)
}
})
console.log(this.state.userAnswers)
}
handleChange(event) {
this.setState({
value: event.target.value
})
}
render() {
const questions = [
Blargh?,
blah blah blah?,
how many dogs?
]
return (
<div class=container-fluid text-center>
<h1>{questions[this.state.questionNumber - 1]}</h1>
<div class=radio>
<label class=radio-inline>
<input type=radio class=form-control name=trueFalse value=true
onChange={this.handleChange}/>True
</label><br/><br/>
<label class=radio-inline>
<input type=radio class=form-control name=trueFalse value=false
onChange={this.handleChange}/>False
</label>
<hr/>
<button type=button class=btn btn-primary
onClick={this.handleContinue}>Continue</button>
</div>
</div>
)
}
}