Using props to conditionally render code is very common. They use the value of a given prop to automatically make decisions about what to render.
In this lesson, FreeCodeCamp wants you set up a child component to make rendering decisions based on props. You'll also use the ternary operator. We have a parent called GameOfChance, and a child Results.
First, we need a simple expression that randomly returns a different value every time it is run. You can use Math.random(). This method returns a value between 0 (inclusive) and 1 (exclusive) each time it is called. So for 50/50 odds, use Math.random() >= .5 in your expression.
Now Render the Results component as a child of GameOfChance, and pass in expression as a prop called fiftyFifty. In the Results component, write a ternary expression to render the h1 element with the text You Win! or You Lose! based on the fiftyFifty prop that's being passed in from GameOfChance.
Finally they want us to make sure the handleClick() method is correctly counting each turn so the user knows how many times they've played.
Code:
classResultsextendsReact.Component{constructor(props){super(props);}render(){{/* Change code below this line */}return<h1></h1>;{/* Change code above this line */}}}classGameOfChanceextendsReact.Component{constructor(props){super(props);this.state={counter:1};this.handleClick=this.handleClick.bind(this);}handleClick(){this.setState(prevState=>{// Complete the return statement:return{counter:prevState}});}render(){constexpression=null;// Change this linereturn(<div><buttononClick={this.handleClick}>Play Again</button>{/* Change code below this line */}{/* Change code above this line */}<p>{'Turn: '+this.state.counter}</p></div>);}}
Answer:
classResultsextendsReact.Component{constructor(props){super(props);}render(){return<h1>{this.props.fiftyFifty?"You Win!":"You Lose!"}</h1>;}}classGameOfChanceextendsReact.Component{constructor(props){super(props);this.state={counter:1};this.handleClick=this.handleClick.bind(this);}handleClick(){this.setState(prevState=>{return{counter:this.state.counter+1}});}render(){constexpression=Math.random()>=.5// Change this linereturn(<div><buttononClick={this.handleClick}>Play Again</button><ResultsfiftyFifty={expression}/>{/* Change code above this line */}<p>{'Turn: '+this.state.counter}</p></div>);}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)