jmona789 jmona789 - 1 year ago 141
React JSX Question

React: Can I check if a state exists before rendering it

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

<NavItem eventKey={4} href="#">{}</NavItem>

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

Answer Source

Sure you can:

let userNavItem
if ( !== undefined) {
  userNavItem = <NavItem eventKey={4} href="#">{}</NavItem>
} else {
  userNavItem = null

Now you can use userNavItem on your navbar component, and it will render only if is defined.