Skip to content

Instantly share code, notes, and snippets.

@na0x2c6
Last active August 24, 2018 09:09
Show Gist options
  • Save na0x2c6/b7f7c305040264d1d97ce421bf4b55e4 to your computer and use it in GitHub Desktop.
Save na0x2c6/b7f7c305040264d1d97ce421bf4b55e4 to your computer and use it in GitHub Desktop.
HOC Sample 2: Props Proxy
function withSubscription(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {
data: selectData(DataSource, props)
}
}
componentDidMount() {
DataSource.addChangeListener(this.handleChange)
}
componentWillUnmount() {
DataSource.removeChangeListener(this.handleChange)
}
handleChange() {
this.setState({
data: selectData(DataSource, this.props)
})
}
render() {
return <WrappedComponent data={this.state.data} {...this.props} />
}
}
}
const Card = ({ card }) => (
<div className="card">
<div className="card-content" style={{ color: card.color }}>
{card.name}
</div>
</div>
)
const List = ({ list, data }) => {
return (
<div className="column"
style={{ backgroundColor: list.color }}>
<header>{`${list.name} (id:${list.id})`}</header>
{data.map((card, idx) =>
<Card card={card} key={idx} />
)}
</div>
)
}
const ListWithSubscription = withSubscription(
List,
(DataSource, props) => DataSource.getCards(props.list.id)
)
const Board = ({ data }) => {
return (
<div className="columns">
{data.map(list =>
<ListWithSubscription list={list} key={list.id} />
)}
</div>
)
}
const BoardWithSubscription = withSubscription(
Board,
(DataSource) => DataSource.getLists()
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment