Tell us what’s happening:
I’m just confused and would like a little more explanation as to why this is happening. When I hard code the random index, the answer variable gets rendered onto the screen from the start, but when I use ‘this.state.randomIndex’ instead, the application works as intended, and the answer only gets displayed once the button is clicked, which is the intended use to pass the challenge. So my question is, what is the difference and why does it behave that way?
Your code so far
const answer = possibleAnswers[this.state.randomIndex]
const answer = possibleAnswers[Math.floor(Math.random() * possibleAnswers.length -1 )]
const inputStyle = {
width: 235,
margin: 5
}
class MagicEightBall extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: '',
randomIndex: ''
}
this.ask = this.ask.bind(this);
this.handleChange = this.handleChange.bind(this);
}
ask() {
if (this.state.userInput) {
this.setState({
randomIndex: Math.floor(Math.random() * 20),
userInput: ''
});
}
}
handleChange(event) {
this.setState({
userInput: event.target.value
});
}
render() {
const possibleAnswers = [
'It is certain',
'It is decidedly so',
'Without a doubt',
'Yes, definitely',
'You may rely on it',
'As I see it, yes',
'Outlook good',
'Yes',
'Signs point to yes',
'Reply hazy try again',
'Ask again later',
'Better not tell you now',
'Cannot predict now',
'Concentrate and ask again',
'Don\'t count on it',
'My reply is no',
'My sources say no',
'Most likely',
'Outlook not so good',
'Very doubtful'
];
// const answer = possibleAnswers[this.state.randomIndex] // << change code here
const answer = possibleAnswers[Math.floor(Math.random() * possibleAnswers.length -1 )]
return (
<div>
<input
type="text"
value={this.state.userInput}
onChange={this.handleChange}
style={inputStyle} /><br />
<button onClick={this.ask}>
Ask the Magic Eight Ball!
</button><br />
<h3>Answer:</h3>
<p>
{ /* change code below this line */ }
{answer}
{ /* change code above this line */ }
</p>
</div>
);
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36
.
Challenge: Use Advanced JavaScript in React Render Method
Link to the challenge: