Hi, I’ve been trying to do this challange:
And the conditional statement in the render method is giving me unexpected results.
Here is the correct solution:
class Results extends React.Component {
constructor(props) {
super(props);
}
render() {
{/* Change code below this line */}
return (
<h1>{this.props.fiftyFifty ? 'You Win!' : 'You Lose!'}</h1>
)
{/* Change code above this line */}
}
}
class GameOfChance extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
counter: this.state.counter + 1 // change code here
});
}
render() {
const expression = Math.random()>=.5; // Change this line
return (
<div>
<button onClick={this.handleClick}>Play Again</button>
{/* Change code below this line */}
<Results fiftyFifty={expression} />
{/* Change code above this line */}
<p>{'Turn: ' + this.state.counter}</p>
</div>
);
}
}
Let’s take a closer look at the render method of Results object:
render() {
return (
<h1>{this.props.fiftyFifty ? 'You Win!' : 'You Lose!'}</h1>
)}
First I’ve tried doing something like this:
return (
{this.props.fiftyFifty ? <h1>'You Win!'</h1> : <h1>'You Lose!'</h1>}
)
But it throws an error. I’ve tried a bunch of different things and I’ve noticed that if i wrap the entire tertiary statement in another container it works. For example:
return (
<h1>{this.props.fiftyFifty ? <h1>'You Win!'</h1> : <h1>'You Lose!'</h1>}</h1>
)
And then I’ve implemented the correct solution, but I still dont understand why my first attempt didn’t work. I know that render() is supposed to return a single JSX element and since the thing that worked was wrapping the entire “{…}” in another container I assume that:
{this.props.fiftyFifty ? <h1>'You Win!'</h1> : <h1>'You Lose!'</h1>}
for some reason doesn’t evaluate to a single element even though I think it should.
What mistake am I making?