Help please onTernary Expression for Conditional Rendering

Help please onTernary Expression for Conditional Rendering
0

#1

Tell us what’s happening:
I’m suffering with how to use the ternary for rendering the buttonTwo or buttonThree depending on the userAge. This is what i did. What to do please??

Your code so far



const inputStyle = {
  width: 235,
  margin: 5
}

class CheckUserAge extends React.Component {
  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);
  }
  handleChange(e) {
    this.setState({
      input: e.target.value,
      userAge: ''
    });
  }
  submit() {
    this.setState({
      userAge: this.state.input
    });
  }
  render() {
    const buttonOne = <button onClick={this.submit}>Submit</button>;
    const buttonTwo = <button>You May Enter</button>;
    const buttonThree = <button>You Shall Not Pass</button>;
    return (
      <div>
        <h3>Enter Your Age to Continue</h3>
        <input
          style={inputStyle}
          type="number"
          value={this.state.input}
          onChange={this.handleChange} /><br />
        {
          (buttonOne && this.state.userAge >=18) ? buttonTwo : buttonThree


        }
      </div>
    );
  }
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/react/use-a-ternary-expression-for-conditional-rendering


#2

The problem is in the following line. It’s not the logic the challenge wants.

Let’s make it easier by breaking the problem down into smaller parts

The challenge wants you to:

  1. Before doing anything, you need to check if the user has not entered or submitted anything yet => and based on that, buttonOne should be rendered.
  2. If the user has submitted a number < 18 => buttonThree should be rendered.
  3. Else, buttonTwo should be rendered.

As you may have noticed, there are three conditions, but the ternary expression can only accept two, it has the following form: X ? Condition-One : Condition-Two.

Do not worry, it’s not a problem at all. In this case, you can nest a ternary expression into another ternary expression. It could have the following form:

X ? Condition-One : (Y ? Condition-Two : Condition-Three).

I hope this was helpful
And it’s up to you now to find the solution to this challenge.

Good Luck!


#3

Thanks! I’ve overcome it. The goal was just to check whether the userAge has been given. If not, render the buttonOne. otherwise, is the userAge<18? renderbuttonThree else render buttonTwo


#4

Good Luck & Happy Coding.