react-patterns icon indicating copy to clipboard operation
react-patterns copied to clipboard

Existence checking examples are not equivalent

Open evandavis opened this issue 9 years ago • 7 comments

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} />}
  }
}

evandavis avatar Oct 17 '16 19:10 evandavis

You're right; they aren't equivalent.

The spirit behind it is that a component should always render, regardless of data. The owner alone should be making decisions about whether or not that component is renderable.

It's unnecessarily confusing to have a component decides—autonomously—wether or not to render.

chantastic avatar Oct 17 '16 19:10 chantastic

a component should always render, regardless of data.

I agree with this and follow this practice. I think the example you should show is my guard example, rather than defaultProps as that is a different result.

evandavis avatar Oct 17 '16 19:10 evandavis

Does this change make the scetion clearer? https://github.com/planningcenter/react-patterns/commit/996008f91a3c392bf20a6c4d9dbbe14b656e08af

chantastic avatar Oct 18 '16 16:10 chantastic

Thanks for catching those errors. They've been fixed.

chantastic avatar Oct 18 '16 16:10 chantastic

Got that last one.

Thanks @evandavis for help making this section better :)

chantastic avatar Oct 19 '16 15:10 chantastic

:+1: I've been a fan of this guide for a while; really happy to see it evolving.

evandavis avatar Oct 19 '16 16:10 evandavis

Thanks! This kinda stuff is always fun. It's great for having conversations like this—really fleshing out what's good and why. I appreciate your involvement.

I have a couple other resources that put a little more regular attention on.

http://reactcheatsheet.com http://reactpatterns.com

I'm working on one for style next :)

chantastic avatar Oct 19 '16 16:10 chantastic