Last active
December 8, 2017 03:11
-
-
Save brybrophy/ab261514c3a39a894a908a2b9bdea303 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from 'react'; | |
import SmartComponent from './SmartComponent'; | |
export default class App extends Component { | |
render() { | |
return <SmartComponent name="World" />; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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} />; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!