Skip to content

Instantly share code, notes, and snippets.

@Didericis
Last active April 26, 2018 17:29
Show Gist options
  • Save Didericis/003dbe0f0140c313bdfede905863b548 to your computer and use it in GitHub Desktop.
Save Didericis/003dbe0f0140c313bdfede905863b548 to your computer and use it in GitHub Desktop.
Passing props examples
// This architecture is fine if you normally pass around an object with the structure of
// bigObj. EX: If you have a BigObj type that always has firstName, lastName, address, state, etc,
class Component1 extends Component {
fullName = () => `${this.props.bigObj.firstName} ${this.props.bigObj.lastName}`;
location = () => `${this.props.bigObj.address} ${this.props.bigObj.state}`;
render() {
return (
<div>
<span>{this.fullName()}</span>
<span>{this.location()}</span>
</div>
);
}
}
// This architecture is a bit better if you don't always have the firstName, lastName, address, and state
// available, or they may be coming from different places. For example, maybe in one place, the address is
// already concatenated, but the firstName and lastName are not. Then it's probably better to keep the
// display component minimal, and massage the data into the format the component expects via a container
class Component2 extends Component {
render() {
const { fullName, location } = this.props;
return (
<div>
<span>{fullName}</span>
<span>{location}</span>
</div>
);
}
}
// This uses recompose to massage the data coming from 'bigObj' into the format Component2 expects
const Component2Container = withProps(({ bigObj }) => ({
fullName: `${this.props.bigObj.firstName} ${this.props.bigObj.lastName}`,
location: `${this.props.bigObj.address} ${this.props.bigObj.state}`,
})(Component2);
// If you find yourself transforming bigObj into fullName in a bunch of different places, you can transform
// just that piece via an hoc
const withFullNameFromBigObj = withProps(({ bigObj }) => ({
fullName: `${this.props.bigObj.firstName} ${this.props.bigObj.lastName}`,
});
const SomeContainerThatGetsBigObj = withFullNameFromBigObj(SomeComponentThatNeedsFullName);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment