2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Use a Ternary Expression for Conditional Rendering
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Use a Ternary Expression for Conditional Rendering
|
2018-10-12 15:37:13 -04:00
|
|
|
This challenge is to use Ternary Expression only instead of using `If/Else` in code,
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Hints
|
|
|
|
|
|
|
|
### Hint 1
|
2018-10-12 15:37:13 -04:00
|
|
|
Ternary operator has three parts, but you can combine several ternary expressions together. Here's the basic syntax:
|
|
|
|
```
|
|
|
|
condition ? expressionIfTrue : expressionIfFalse
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
First you need declare state in constructor like this
|
|
|
|
|
2019-05-15 10:08:19 -07:00
|
|
|
```jsx
|
2018-10-12 15:37:13 -04:00
|
|
|
constructor(props) {
|
|
|
|
super(props);
|
|
|
|
// change code below this line
|
|
|
|
this.state = {
|
|
|
|
input: '',
|
|
|
|
userAge: ''
|
|
|
|
}
|
|
|
|
// change code above this line
|
|
|
|
this.submit = this.submit.bind(this);
|
|
|
|
this.handleChange = this.handleChange.bind(this);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
Then the ternary operator
|
2019-05-15 10:08:19 -07:00
|
|
|
```jsx
|
2018-10-12 15:37:13 -04:00
|
|
|
{
|
|
|
|
/* change code here */
|
|
|
|
(this.state.userAge >= 18) ? buttonTwo : (this.state.userAge== '')? buttonOne: buttonThree
|
|
|
|
|
|
|
|
}
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|