Skip to content

Instantly share code, notes, and snippets.

@brybrophy
Last active December 8, 2017 03:11
Show Gist options
  • Save brybrophy/ab261514c3a39a894a908a2b9bdea303 to your computer and use it in GitHub Desktop.
Save brybrophy/ab261514c3a39a894a908a2b9bdea303 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import SmartComponent from './SmartComponent';
export default class App extends Component {
render() {
return <SmartComponent name="World" />;
}
}
import React from 'react';
import PropTypes from 'prop-types';
export default function DumbComponent({ greeting, name}) {
return <h1>{greeting} {name}</h1>
}
DumbComponent.propTypes = {
greeting: PropTypes.string,
name: PropTypes.string
}
export default function buildProps(props, propKeys) {
const flatProps = props.isArray() ? Object.assign({}, ...props) : props;
const builtProps = {};
for (const key of propKeys) {
if (key in flatProps) {
builtProps[key] = flatProps[key];
}
}
return builtProps;
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import buildProps from '../lib/propsBuilder';
import DumpComponent from './DumpComponent';
export default class SmartComponent extends Component {
state = {
greeting: 'Hello, ';
}
dumbComponentProps = buildProps(
[this.props, this.state],
Object.keys(DumbComponent.propTypes)
);
render() {
return <DumbComponent {...this.dumbComponentProps} />;
}
}
@pbabbott
Copy link

pbabbott commented Dec 8, 2017

I really like this approach largely for the line DumbComponent.propTypes if we were to copy-paste this pattern around to the smart components in the app, it would strongly encourage prop-type usage in the dumb components. This, in my mind, is a move toward best practices in that the more dumb components that have prop types - the better!

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