Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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="#">{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?

like image 856
jmona789 Avatar asked Oct 03 '16 18:10

jmona789


People also ask

How do you check if something exists in React?

To check if an element exists in an array in React: Use the includes() method to check if a primitive exists in an array. Use the some() method to check if an object exists in an array.

How do you check if the state has changed React?

Use the useEffect hook to listen for state changes in React. You can add the state variables you want to track to the hook's dependencies array and the logic in your useEffect hook will run every time the state variables change.


2 Answers

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>
  );
}
like image 173
Scarysize Avatar answered Oct 02 '22 19:10

Scarysize


Sure you can:

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

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

like image 38
Mchl Avatar answered Oct 02 '22 19:10

Mchl