Existence checking examples are not equivalent
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} />}
}
}
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.
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.
Does this change make the scetion clearer? https://github.com/planningcenter/react-patterns/commit/996008f91a3c392bf20a6c4d9dbbe14b656e08af
Thanks for catching those errors. They've been fixed.
Got that last one.
Thanks @evandavis for help making this section better :)
:+1: I've been a fan of this guide for a while; really happy to see it evolving.
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 :)