Krishna Kr
Krishna Kr

Reputation: 21

Ternary Operator second part not rendering React JS

The Second part i.e sign up part is not rendering

The intention is to get the span being changed on click each tab i.e sign ,sign up and forget This is the main class and the form class is called in it. The below code is the original code used to render in the screen


   class App extends React.Component {
 constructor(props) {
   super(props);
   // this.setOptionSignIn = this.setOptionSignIn.bind(this);
   // this.setOptionSignUp = this.setOptionSignUp.bind(this);
   // this.setOptionForget = this.setOptionForget.bind(this);

   this.state = {
     option : 1    
   }
 }

setOptionSignIn = () => {
 this.setState(()=> {
   return {
     option : 1
   }
 })
}
setOptionSignUp = () => {
 this.setState(()=> {
   return {
     option : 2
   }
 })
}
setOptionForget = () => {
 this.setState(()=> {
   return {
     option : 3
   }
 })
}
render() {
 return (
     <div className="container">
     {
       console.log(this.state.option+"before and type is "+ typeof this.state.option)
     }
     <header className={
 `header-headings ${this.state.option === 1 ? 'sign-in' : this.state.option === 2 ? 'sign-up' : 'forgot'}`}>       
         <span>Sign in to your account</span>
         <span>Create an account</span>    
         <span>Reset your password</span>
     </header>   
     {
       console.log(this.state.option+"after and type is "+ typeof this.state.option)
     }
     <ul className="options">
     <li className={this.state.option === 1 ? 'active' : ''} onClick={this.setOptionSignIn}>Sign in</li>
     <li className={this.state.option === 2 ? 'active' : ''} onClick={this.setOptionSignUp}>Sign up</li>
     <li className={this.state.option === 3 ? 'active' : ''} onClick={this.setOptionForget}>Forget</li> 
     </ul>
     <Form optionState={this.state.option} />
     </div>
 )}
}



Upvotes: 0

Views: 416

Answers (2)

Atin Singh
Atin Singh

Reputation: 3690

To switch the span based on the option insert the condition in span.

 <span>{this.state.option === 1 ? 'Sign in to your account' : this.state.option === 2 ? 'Create an account' : 'Reset your password'}</span>

Hope this helps you.

Upvotes: 0

Andrei Todorut
Andrei Todorut

Reputation: 4536

The ternary condition you are using above is correct. The problem may be related to the state which is not properly updated.

The state has to be updated using this.setState() method and not by changing the state properties directly on the this.state object.

Please check out the code below:

SignIn method:

setOptionSignIn() {
   this.setState({
     option: 1
   });
}

SignUp method

setOptionSignUp() {
   this.setState({
      option: 2
   });
}

ForgetPassword method:

setOptionForget() {
   this.setState({
      option: 0
   });
}

Upvotes: 2

Related Questions