Skip to content

Existence checking examples are not equivalent #35

Description

@evandavis

Under Existence Checking, you provide the following example:

// bad
render () {
  if (this.props.person) {
    return <div>{this.props.person.firstName}</div>;
  } else {
    return null;
  }
}
// good
class MyComponent extends React.Component {
  render() {
    return <div>{this.props.person.firstName}</div>;
  }
}

MyComponent.defaultProps = {
  person: {
    firstName: 'Guest'
  }
};

However, these results are not equivalent. One renders nothing, the other renders a default value. I would like to see best practices for both cases.


On a related note, is there a best practice for bailing out of render vs guarding in the calling component?

Ie return null from the child

function Child ({someProp}) {
   return someProp ? <div>{someProp}</div> : null;
}

class Parent extends Component {
  render() {
    return <Component someProp={someProp} />
  }
}

vs guarding in the parent

function Child ({someProp}) {
   return <div>{someProp}</div>;
}

class Parent extends Component {
  render() {
    return {someProp && <Component someProp={someProp} />}
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions