The ternary operator is often utilized as a shortcut for if/else statements in JavaScript.
Ternary expressions can be a great alternative if you want to implement conditional logic within your JSX. Ternary operator has three parts, but you can combine several ternary expressions together. Here's the basic syntax:
condition ? expressionIfTrue : expressionIfFalse;
In this lesson FreeCodeCamp wants us to set up a ternary expression that implements the following logic: when the page first loads, render the submit button, buttonOne, to the page. Then, when a user enters their age and clicks the button, render a different button based on the age. If a user enters a number less than 18, render buttonThree. If a user enters a number greater than or equal to 18, render buttonTwo.
First we have to initialize the state of CheckUserAge with input and userAge both set to values of an empty string.
constinputStyle={width:235,margin:5};classCheckUserAgeextendsReact.Component{constructor(props){super(props);// Change code below this line// Change code above this linethis.submit=this.submit.bind(this);this.handleChange=this.handleChange.bind(this);}handleChange(e){this.setState({input:e.target.value,userAge:''});}submit(){this.setState(state=>({userAge:state.input}));}render(){constbuttonOne=<buttononClick={this.submit}>Submit</button>;constbuttonTwo=<button>You May Enter</button>;constbuttonThree=<button>You Shall Not Pass</button>;return(<div><h3>Enter Your Age to Continue</h3><inputstyle={inputStyle}type='number'value={this.state.input}onChange={this.handleChange}/><br/>{/* Change code below this line */}{/* Change code above this line */}</div>);}}
render(){constbuttonOne=<buttononClick={this.submit}>Submit</button>;constbuttonTwo=<button>You May Enter</button>;constbuttonThree=<button>You Shall Not Pass</button>;return(<div><h3>Enter Your Age to Continue</h3><inputstyle={inputStyle}type='number'value={this.state.input}onChange={this.handleChange}/><br/>{this.state.userAge===''?buttonOne:this.state.userAge<18?buttonThree:buttonTwo}</div>);}}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)