Accessing value inside of object property using ternary (Authorization Form)

class Contact extends React.Component { constructor(props) { super(props); this.state = { password: 'swordfish', authorized: false }; this.authorize = this.authorize.bind(this); } let text = this.state.authorized ? 'yes' : 'no'; render() { return ( <div id="authorization"> <h1>{text}</h1> </div> ) }} ReactDOM.render( <Contact />, document.getElementById('app') );

nothing is displayed. what is wrong with my logic here? thank you

let text = this.state.authorized ? 'yes' : 'no';
This has to be inside the render function above the return statement. A variable declaration with let keyword inside a class component causes a syntax error.

1 Like

if i want to run 2 things on 1 side the ternary (either T/F), would this be correct?


//toggle boolean
changeAut(){
return (!this.state.authorized);
}
render() {
let text = this.state.authorized ? ‘yes’ && changeAut(): ‘no’;


I guess you can write a ternary like that. But I don’t think that it’s a very elegant way of doing it as a ternary should be kept as simple as possible. And I doubt that it works in this context. Another problem is that you don’t actually toggle the state. With your changeAuth function you just return the state rather than really toggling it. You should set the state instead:

//toggle boolean
changeAut(){
  setState(!this.state.authorized);
}

Then I would have a simple ternary that just returns the text:

let text = this.state.authorized ? 'yes' : 'no';

And an onClick event handler that toggles the state:

<button onClick={this.changeAut}>{text}</button>