Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  25] [ 5]  / answers: 1 / hits: 43244  / 8 Years ago, mon, october 3, 2016, 12:00:00

I'm new to React and I've made a navbar that displays the users name user



<NavItem eventKey={4} href=#>{this.state.name}</NavItem>


but the problem is if the user is not signed in, I get an error due to this.state.name being undefined. Is there some way I can check if this.state.name is defined before rendering it as part of the navbar or is there a better way to get rid of this error?


More From » reactjs

 Answers
2

Sure, use a ternary:



render() {
return (
this.state.name ? <NavItem>{this.state.name}</NavItem> : null
);
}


or even shorter



render() {
return (
this.state.name && <NavItem>{this.state.name}</NavItem>
);
}

[#60519] Friday, September 30, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzjenseny

Total Points: 409
Total Questions: 93
Total Answers: 106

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;