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

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


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>  );}


Sure you can:

let userNavItemif (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.


In React, you can check if a state exists before push

    checkedProduct=(prop)=>{  var checkIfExist = this.state.checkedProduct.filter((product)=>{    return product===prop  })  if(checkIfExist.length>0){    var checkIfExist = this.state.checkedProduct.filter((product)=>{      return product!==prop    })    this.setState({ checkedProduct:checkIfExist })  }else{    this.setState({ checkedProduct: this.state.checkedProduct.concat(prop) })  }}