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} />;
}
}
@brybrophy
Copy link
Author

This is an idea for passing props to dumb components based on it's prop types. This would prevent us from having to deconstruct props in every place we are using a dumb component, and ensure that we are creating prop types for all dumb components. When we add or remove props from a dumb component, we won't need to hunt down every place it is being used to update the props, we only need to update the prop types.

@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