React: Render Conditionally from Props
Randy Rivera
Posted on November 16, 2021
- 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 childResults
. - 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 ofGameOfChance
, and pass in expression as a prop calledfiftyFifty
. In the Results component, write a ternary expression to render the h1 element with the text You Win! or You Lose! based on thefiftyFifty
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:
class Results extends React.Component {
constructor(props) {
super(props);
}
render() {
{/* Change code below this line */}
return <h1></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(prevState => {
// Complete the return statement:
return {
counter: prevState
}
});
}
render() {
const expression = null; // Change this line
return (
<div>
<button onClick={this.handleClick}>Play Again</button>
{/* Change code below this line */}
{/* Change code above this line */}
<p>{'Turn: ' + this.state.counter}</p>
</div>
);
}
}
- Answer:
class Results extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h1>{this.props.fiftyFifty ? "You Win!" : "You Lose!"}</h1>;
}
}
class GameOfChance extends React.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() {
const expression = Math.random() >= .5 // Change this line
return (
<div>
<button onClick={this.handleClick}>Play Again</button>
<Results fiftyFifty = {expression} />
{/* Change code above this line */}
<p>{'Turn: ' + this.state.counter}</p>
</div>
);
}
}
๐ ๐ช ๐
๐ฉ
Randy Rivera
Posted on November 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How to build a website using React and Rest APIs (React basics explained)
November 6, 2024