phantom phantom - 2 months ago 12
Javascript Question

clear input box on certain condition react

I am making a

get
request to a quiz api. When the user gets the answer correct the next answer is shown.

This is all working well, however I have got into some trouble when trying to clear the input box when the user gets the answer correct. I read this earlier and as far as I can tell it should be following the same logic.

Can anyone spot what is wrong here?

var Quiz = React.createClass({

getInitialState: function() {
return {
question: '',
answer: '',
value: '',
score: 0
}
},

getData: function() {
$.get('http://jservice.io/api/random', function(data){
var response = data[0];
console.log(response)

this.setState({
question: response.question,
answer: response.answer
})
}.bind(this));
},

componentDidMount: function() {
this.serverRequest = this.getData()
},

checkAnswer: function(event) {
if(event.target.value.toLowerCase() === this.state.answer.toLowerCase()) {
this.setState({
score: this.state.score + 1,
value: ''
})
this.getData();
}
},

skipQuestion: function() {
this.getData();
},

render: function() {
var value = this.state.value
return (
<div>
<p>{this.state.question}</p>
<input type='text' value={value} onChange={this.checkAnswer}/>
<p onClick={this.skipQuestion}>New question</p>
<p>{this.state.score}</p>
</div>
)
}

});

Answer

I moved this code into a jsbin and your input clearing logic is working fine. However, as @finalfreq mentioned in your implementation it's impossible to type a full answer in to the input box, each input gets recognized but is never displayed. The fix for that is shown below. The only change is adding the else case in checkAnswer:

var Quiz = React.createClass({

getInitialState: function() {
    return {
            question: '',
            answer: '',
            value: '',
            score: 0
        }
},

getData: function() { 
    $.get('http://jservice.io/api/random', function(data){
        var response = data[0];
        console.log(response)

        this.setState({
            question: response.question,
            answer: response.answer
        })
    }.bind(this));
},

componentDidMount: function() {
    this.serverRequest = this.getData()
},

checkAnswer: function(event) {
    if(event.target.value.toLowerCase() === this.state.answer.toLowerCase()) {
        this.setState({
            score: this.state.score + 1,
            value: ''
        })
        this.getData();
    } else {
        this.setState({
            value: event.target.value.toLowerCase()
        })
    }
},

skipQuestion: function() {
    this.getData();
},

render: function() {
    var value = this.state.value
    return (
        <div>
            <p>{this.state.question}</p>
            <input type='text' value={value}  onChange={this.checkAnswer}/>
            <p onClick={this.skipQuestion}>New question</p>
            <p>{this.state.score}</p>
        </div>
    )
}

});