What happens when I add and remove "this"

In the submit function, I tried “userAge: this.state.input” and “userAge: state.input”, both of them work well in the challege, could you tell me why, and what happened or what is the difference bettween them? Thanks!

  **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 = {
    userAge: '',
    input: ''
  }
  // 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(state => ({
    userAge: 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 />
      {/* Change code below this line */}
      {
      this.state.userAge === ''
        ? buttonOne
        : this.state.userAge >= 18
          ? buttonTwo
          : buttonThree
      }
      {/* Change code above this line */}
    </div>
  );
}
}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Use a Ternary Expression for Conditional Rendering

Link to the challenge:

I think, since this would be referring to the object, this.state.input would refer to a value belonging to the instance of CheckUserAge. While just using state.input would refer to the atribute input belonging to the state variable that was passed to setState.

It might be worth using some console.log()s to see what values are being used.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.